[英]How to use the “is” operator in System.Type variables?
这是我在做什么:
object ReturnMatch(System.Type type)
{
foreach(object obj in myObjects)
{
if (obj == type)
{
return obj;
}
}
}
但是,如果obj是type
的子type
,则它将不匹配。 但是我希望函数以与使用操作符is
相同的方式返回。
我尝试了以下操作,但无法编译:
if (obj is type) // won't compile in C# 2.0
我想到的最好的解决方案是:
if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))
难道没有一种使用运算符的is
可以使代码更整洁?
遇到此问题时,我已使用IsAssignableFrom方法。
Type theTypeWeWant; // From argument or whatever
foreach (object o in myCollection)
{
if (theTypeWeWant.IsAssignableFrom(o.GetType))
return o;
}
可能会或可能不会解决您的问题的另一种方法是使用通用方法:
private T FindObjectOfType<T>() where T: class
{
foreach(object o in myCollection)
{
if (o is T)
return (T) o;
}
return null;
}
(代码是从内存写入的,未经测试)
也许
type.IsAssignableFrom(obj.GetType())
您没有在使用is运算符,而是使用Type.IsInstanceOfType方法。
http://msdn.microsoft.com/en-us/library/system.type.isinstancetancetype.aspx
is运算符指示将一个对象强制转换为另一个对象(通常是超类)是否“安全”。
if(obj is type)
如果obj是'type'类型或其子类,则if语句将成功,因为将obj强制转换为(type)obj是'safe'。
请参阅: http : //msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx
为什么不能使用关键字“ is”本身呢?
foreach(object obj in myObjects)
{
if (obj is type)
{
return obj;
}
}
编辑-我看到了我所缺少的。 Isak的建议是正确的。 我已经测试并确认。
class Level1
{
}
class Level2A : Level1
{
}
class Level2B : Level1
{
}
class Level3A2A : Level2A
{
}
class Program
{
static void Main(string[] args)
{
object[] objects = new object[] {"testing", new Level1(), new Level2A(), new Level2B(), new Level3A2A(), new object() };
ReturnMatch(typeof(Level1), objects);
Console.ReadLine();
}
static void ReturnMatch(Type arbitraryType, object[] objects)
{
foreach (object obj in objects)
{
Type objType = obj.GetType();
Console.Write(arbitraryType.ToString() + " is ");
if (!arbitraryType.IsAssignableFrom(objType))
Console.Write("not ");
Console.WriteLine("assignable from " + objType.ToString());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.