Type.IsAssignableFrom不使用Predicate<>

时间:2012-09-24 20:37:13

标签: c# generics

以下代码片段,我相信应该可行,但失败了。我也尝试过IsInstanceOfType。

Assert.IsTrue(typeof(Predicate<>).IsAssignableFrom(typeof(Predicate<int>)), "No predicate match!");

我的断言错了吗?

2 个答案:

答案 0 :(得分:3)

不,那不行 - 你永远不会有开放类型的值,所以这不起作用。

听起来你可能想要Type.GetGenericTypeDefinition

if (type.IsGenericType &&
    type.GetGenericTypeDefinition() == typeof(Predicate<>))
{
    ...
}

答案 1 :(得分:0)

我认为这种方法不应该起作用。

对于A类型与B类型之间的关系:

A.IsAssignableFrom(B) == trueAB的基类,或AB的接口

有点像:

public class Animal { }
public class Dog : Animal { }

那样:

typeof(Animal).IsAssignableFrom(typeof(Dog)) == true;

// you can do
Dog spot = new Dog();
Animal a = spot;        // assigned an Animal from a Dog

// but not
Animal b = new Animal();
Dog spike = b;          // compiler complains