如何使用&QUOT是"运营商System.Type的变量? [英] How to use the "is" operator in System.Type variables?

查看:97
本文介绍了如何使用&QUOT是"运营商System.Type的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在做什么:

object ReturnMatch(System.Type type)  
{  
    foreach(object obj in myObjects)  
    {
        if (obj == type)  
        {  
            return obj;  
        }  
    }  
}



但是,如果obj是一个类型的子类,它不会匹配。但我想函数返回,如果我用的是运营商以同样的方式。

However, if obj is a subclass of type, it will not match. But I would like the function to return the same way as if I was using the operator is.

我试过下面,但它不会编译:

I tried the following, but it won't compile:

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

我想出了最好的解决办法:

The best solution I came up with was:

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

是不是有使用运营商的方式来使代码更清洁?

Isn't there a way to use operator is to make the code cleaner?

推荐答案

我用的时候碰到这样的问题IsAssignableFrom方法。

I've used the IsAssignableFrom method when faced with this problem.

Type theTypeWeWant; // From argument or whatever
foreach (object o in myCollection)
{
    if (theTypeWeWant.IsAssignableFrom(o.GetType))
         return o;
}

这可能或可能不与您的问题的工作的另一种方法是用一个通用的方法:

Another approach that may or may not work with your problem is to use a generic method:

private T FindObjectOfType<T>() where T: class
{
    foreach(object o in myCollection)
    {
        if (o is T)
             return (T) o;
    }
    return null;
}



(代码从存储器写入,未测试)

(Code written from memory and is not tested)

这篇关于如何使用&QUOT是&QUOT;运营商System.Type的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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