2013-09-24 51 views
9

我有下面的代碼,其中T是被定義爲這樣一個通用:爲什麼我的C#IS語句不起作用?

public abstract class RepositoryBase<T> where T : class, IDataModel 

此代碼工作得很好:

PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName); 
if (propertyInfo.DeclaringType.FullName == typeof(T).FullName) <--- Works just fine 

VS此代碼的值爲false

PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName); 
if (propertyInfo.DeclaringType is T) <-- does not work 

我在這裏做錯了什麼?

+0

http://www.youtube.com/watch?v=j4XT-l-_3y0 – JoelFan

回答

24

is使用兩個對象之間的類型比較。因此​​的類型爲Typetypeof(T)的類型爲T,它們不相等。

var aType = typeof(propertyInfo.DeclaringType); 
var bType = typeof(T); 
bool areEqual = aType is bType; // Always false, unless T is Type 
4

你所尋找的是

TypeIsAssignableFrom

if (propertyInfo.DeclaringType.IsAssignableFrom(typeof(T))) 
相關問題