以下代码片段,我相信应该可行,但失败了。我也尝试过IsInstanceOfType。
Assert.IsTrue(typeof(Predicate<>).IsAssignableFrom(typeof(Predicate<int>)), "No predicate match!");
我的断言错了吗?
答案 0 :(得分:3)
不,那不行 - 你永远不会有开放类型的值,所以这不起作用。
听起来你可能想要Type.GetGenericTypeDefinition
:
if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Predicate<>))
{
...
}
答案 1 :(得分:0)
我认为这种方法不应该起作用。
对于A
类型与B
类型之间的关系:
A.IsAssignableFrom(B) == true
,A
是B
的基类,或A
是B
的接口
有点像:
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