【发布时间】:2018-07-26 17:29:36
【问题描述】:
我有以下通用类:
public class SearchResult<T>
{
public int ResultCount { get; set; }
public IEnumerable<T> Result { get; set; }
}
我还有一个Bird类,它实现了IFlyble接口:
public class Bird : IFlyable
{
public void Fly() {}
}
public interface IFlyable
{
void Fly();
}
我还有一个 res 类型的变量 object。
如何检查res 是否为SearchResult<IFlyable>?
我试过这样:
if (res.GetType().IsAssignableFrom(typeof(SearchResult<IFlyable>)))
{
///
}
这样:
if(res is SearchResult<IFlyable>)
{
///
}
但它似乎不起作用。
【问题讨论】:
-
@maccettura res 是
object并且没有Result属性。 -
@mjwills 我想检查特定的
object是否是SearchResult<Flyable> -
res的具体具体类型是什么?是object res = new SearchResult<IFlyable>()还是实际上是object res = new SearchResult<Bird>()。 -
另一方面,如果您必须在使用泛型时进行类型检查,那么您很可能做出了错误的设计决定,因此解释您为什么要这样做可能会让我们建议另一种方法。
-
@juharr
object res = new SearchResult<Bird>()
标签: c# generics interface casting