如何判断俩个类型是否兼容

gh1223181184 2017-11-30 10:45:58
比如 类型1是int ,类型2是int? 如何判断这类型1是否可以转换为类型2
...全文
332 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
正怒月神 2017-11-30
  • 打赏
  • 举报
回复
引用 10 楼 starfd 的回复:
突然发现这个问题有意思 implicit explicit这种反射应该怎么反射出来?查了下不知道该怎么反射啊
可能这个需要看源码了。因为不知道思路
  • 打赏
  • 举报
回复
突然发现这个问题有意思 implicit explicit这种反射应该怎么反射出来?查了下不知道该怎么反射啊
_jiasong 2017-11-30
  • 打赏
  • 举报
回复
引用 3 楼 gh1223181184 的回复:
[quote=引用 2 楼 guwei4037 的回复:] C#有is关键字来判断,用as关键字来转换。 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/is https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/as
你这是判断对象是否是某个类型 , 我问的是类型是否是某个类型[/quote] 将该类型实例化对象判断呗,Activator.CreateInstance(Type t)
正怒月神 2017-11-30
  • 打赏
  • 举报
回复
IsAssignableFrom:确定指定类型的实例是否可以分配给当前类型的实例
static void Main(string[] args)
        {
            Type a = typeof(A);
            Type b = typeof(B);
            Console.WriteLine(a.IsAssignableFrom(b));       //true
            Console.WriteLine(b.IsAssignableFrom(a));       //false

            Type c = typeof(Nullable<int>);
            Type d = typeof(int);
            Console.WriteLine(c.IsAssignableFrom(d));       //true
            Console.WriteLine(d.IsAssignableFrom(c));       //false

            Console.ReadLine();
        }

        class A { }

        class B : A { }
exception92 2017-11-30
  • 打赏
  • 举报
回复
无解吧。

gh1223181184 2017-11-30
  • 打赏
  • 举报
回复
引用 4 楼 guwei4037 的回复:
a.GetType().Equals(b.GetType()) ?
、这是俩类型是否一样 , 不是是否兼容
gh1223181184 2017-11-30
  • 打赏
  • 举报
回复
引用 5 楼 starfd 的回复:
我想知道你用的场景,这个是IDE编译级别的问题……
突发奇想 没啥应用啊
  • 打赏
  • 举报
回复
我想知道你用的场景,这个是IDE编译级别的问题……
全栈极简 2017-11-30
  • 打赏
  • 举报
回复
a.GetType().Equals(b.GetType()) ?
gh1223181184 2017-11-30
  • 打赏
  • 举报
回复
引用 2 楼 guwei4037 的回复:
C#有is关键字来判断,用as关键字来转换。 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/is https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/as
你这是判断对象是否是某个类型 , 我问的是类型是否是某个类型
全栈极简 2017-11-30
  • 打赏
  • 举报
回复
C#有is关键字来判断,用as关键字来转换。 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/is https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/as
ourhouzi 2017-11-30
  • 打赏
  • 举报
回复
if(1 is int32)
xuzuning 2017-11-30
  • 打赏
  • 举报
回复
implicit(隐式转换)、 explicit(显式转换)是你指定的,当然可以反射出来 https://kb.cnblogs.com/page/42277/
闭包客 2017-11-30
  • 打赏
  • 举报
回复
看源代码判断。
wanghui0380 2017-11-30
  • 打赏
  • 举报
回复
不掉书袋子,请lz自己给个例子,实际说明你到底要判定啥 也许人家很简单呢,只想判定一下 A的实例能不能转换成B的实例呢?
gh1223181184 2017-11-30
  • 打赏
  • 举报
回复
引用 10 楼 starfd 的回复:
突然发现这个问题有意思 implicit explicit这种反射应该怎么反射出来?查了下不知道该怎么反射啊
我觉得C# 应该支持这种检测
gh1223181184 2017-11-30
  • 打赏
  • 举报
回复
引用 12 楼 hanjun0612 的回复:
[quote=引用 10 楼 starfd 的回复:] 突然发现这个问题有意思 implicit explicit这种反射应该怎么反射出来?查了下不知道该怎么反射啊
可能这个需要看源码了。因为不知道思路[/quote] 这个我好像以前遇到过一次 忘记在哪了

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧