2012-09-24 51 views
1

下面的代碼片段工作,我相信應該工作,但失敗。我也嘗試過IsInstanceOfType。Type.IsAssignableFrom不謂<>

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

我的斷言錯了嗎?

回答

3

不,那是行不通的 - 你不可能有開放類型的值,因此可能無法正常工作。

這聽起來像你可能想Type.GetGenericTypeDefinition

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

關閉! 。p.GetType()IsGenericType && p.GetType()GetGenericTypeDefinition()== typeof運算(謂語<>) – dvallejo

+0

@DanVallejo:所有你需要的是'類型類型= p.GetType()'先:)(沒有什麼有關'p'的問題 - 我們真的不知道你想幹什麼) –

+0

對不起,我的觀點是,它是IsGenericType,你原來有IsConstructedGenericType或類似的東西。謝謝,它向我指出了正確的方向:) – dvallejo

0

我不認爲這是該方法應該是怎樣工作的。

對於A類型和類型B之間的關係:

A.IsAssignableFrom(B) == trueA是一個基類的B,或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 
+0

一個應該是一個基類的B,否則你永遠不會有多態性。 – dvallejo

相關問題