这是我正在做的事情:
object ReturnMatch(System.Type type)
{
foreach(object obj in myObjects)
{
if (obj == type)
{
return obj;
}
}
}
但是,如果obj是type
的子类,则它将不匹配。但我希望函数的返回方式与使用运算符is
时的方式相同。
我尝试了以下内容,但无法编译:
if (obj is type) // won't compile in C# 2.0
我想出的最佳解决方案是:
if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))
是否有办法使用运算符is
来使代码更清晰?
答案 0 :(得分:4)
在遇到这个问题时我使用了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;
}
(代码从内存中写入,未经过测试)
答案 1 :(得分:2)
也许
type.IsAssignableFrom(obj.GetType())
答案 2 :(得分:2)
不使用is运算符,但Type.IsInstanceOfType方法似乎是您正在寻找的。 p>
http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx
答案 3 :(得分:0)
is运算符指示将一个对象转换为另一个对象(通常是超类)是否“安全”。
if(obj is type)
如果obj是'type'类型或其子类,则if语句将成功,因为将obj强制转换为(type)obj是“安全的”。
请参阅:http://msdn.microsoft.com/en-us/library/scekt9xw(VS.71).aspx
答案 4 :(得分:0)
您是否有理由不能使用“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());
}
}
}