作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我正在做的:
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/
我是一名优秀的程序员,十分优秀!