“是"之间的区别在于和"IsAssignableFrom"C# [英] Difference between "is" and "IsAssignableFrom" C#

查看:41
本文介绍了“是"之间的区别在于和"IsAssignableFrom"C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间有什么区别

typeof(IInterface).IsAssignableFrom(typeof(Class));

typeof(Class) is IInterface

?

对于上下文,我的功能是这样的:

for context, my function is something like this:

public static List<T> GetAllInstancesOfType<T>() where T:Entity
{
  List<T> l = new List<T>();

  if (typeof(IMyInterface).IsAssignableFrom(typeof(T)) //or (typeof(T) is IMyInterface)
     foreach(Entity e in List1) if (e is T) l.Add(e as T);

  else foreach (Entity e in List2) if (e is T) l.Add(e as T);

  return l;
}

推荐答案

它们看起来很相似,但是概念上却大不相同.前者回答了一个问题:如果我有这种类型的变量,我可以为其分配这种类型的 value 吗?"

They are similar-looking but conceptually very different. The former answers the question "if I had a variable of this type, could I assign to it a value of that type?"

后者回答问题可以通过引用或装箱转换将这个实际值转换为这种类型吗?"

The latter answers the question "can this actual value be converted to this type via reference or boxing conversion?"

在后一种情况下,实际对象是类型为 Type 的对象,而不是类型为 Class 的对象.确保您了解以下两者之间的区别:

In the latter case, the actual object is an object of type Type, not an object of type Class. Make sure you understand the difference between:

Type t = typeof(Class);
Class c = new Class();
bool b1 = t is IInterface;
bool b2 = c is IInterface;

第一个询问能否将 Type 对象转换为接口?"第二个询问是否可以将 Class 对象转换为接口?"

The first asks "can the Type object be converted to the interface?" and the second asks "can the Class object be converted to the interface?"

这篇关于“是"之间的区别在于和"IsAssignableFrom"C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆