gpt4 book ai didi

c# - 如何在 System.Type 变量中使用 "is"运算符?

转载 作者:行者123 更新时间:2023-11-30 14:05:26 24 4
gpt4 key购买 nike

这是我正在做的:

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来使代码更简洁?

最佳答案

遇到这个问题时,我使用了 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;
}

(从内存中编写的代码,未经测试)

关于c# - 如何在 System.Type 变量中使用 "is"运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com