当前位置:首页> 正文

关于c#:如何在System.Type变量中使用” is”运算符?

关于c#:如何在System.Type变量中使用” is”运算符?

How to use the “is” operator in System.Type variables?

这是我正在做的事情:

1
2
3
4
5
6
7
8
9
10
object ReturnMatch(System.Type type)  
{  
    foreach(object obj in myObjects)  
    {
        if (obj == type)  
        {  
            return obj;  
        }  
    }  
}

但是,如果obj是type的子类,则它将不匹配。但是我希望函数以与使用操作符is

相同的方式返回

我尝试了以下操作,但无法编译:

1
if (obj is type) // won't compile in C# 2.0

我想到的最好的解决方案是:

1
if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))

是否无法使用运算符is来使代码更简洁?


遇到此问题时,我已使用IsAssignableFrom方法。

1
2
3
4
5
6
Type theTypeWeWant; // From argument or whatever
foreach (object o in myCollection)
{
    if (theTypeWeWant.IsAssignableFrom(o.GetType))
         return o;
}

可能会或可能不会解决您问题的另一种方法是使用通用方法:

1
2
3
4
5
6
7
8
9
private T FindObjectOfType< T >() where T: class
{
    foreach(object o in myCollection)
    {
        if (o is T)
             return (T) o;
    }
    return null;
}

(从内存写入的代码未经测试)


不使用is运算符,但是Type.IsInstanceOfType方法似乎正是您要寻找的。

http://msdn.microsoft.com/zh-cn/library/system.type.isinstancetanceoftype.aspx


也许

1
type.IsAssignableFrom(obj.GetType())

您是否有理由无法使用" is"关键字本身?

1
2
3
4
5
6
7
foreach(object obj in myObjects)
{
  if (obj is type)
  {
    return obj;
  }
}

编辑-我看到了我所缺少的。 Isak的建议是正确的。我已经测试并确认。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
  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());

      }
    }
  }

is运算符指示将一个对象强制转换为另一个对象(通常是超类)是否"安全"。

1
if(obj is type)

如果obj是'type'类型或其子类,则if语句将成功,因为将obj强制转换为(type)obj是'safe'。

请参阅:http://msdn.microsoft.com/zh-cn/library/scekt9xw(VS.71).aspx


展开全文阅读

相关内容