2013-03-11 63 views
40

我試試就知道了,如果一個屬性類存在的存在,我想這一點:檢查屬性的一類

public static bool HasProperty(this object obj, string propertyName) 
{ 
    return obj.GetType().GetProperty(propertyName) != null; 
} 

我不明白爲什麼第一次測試方法不及格?

[TestMethod] 
public void Test_HasProperty_True() 
{ 
    var res = typeof(MyClass).HasProperty("Label"); 
    Assert.IsTrue(res); 
} 

[TestMethod] 
public void Test_HasProperty_False() 
{ 
    var res = typeof(MyClass).HasProperty("Lab"); 
    Assert.IsFalse(res); 
} 
+2

你介意張貼從'MyClass'相關的代碼? – nattyddubbs 2013-03-11 14:31:53

回答

62

你的方法是這樣的:

public static bool HasProperty(this object obj, string propertyName) 
{ 
    return obj.GetType().GetProperty(propertyName) != null; 
} 

這增加了一個擴展到object - 基類一切的。當你調用這個擴展你傳遞一個Type

var res = typeof(MyClass).HasProperty("Label"); 

你的方法需要一個類,而不是一個Type實例。否則,你基本上做

typeof(MyClass) - this gives an instanceof `System.Type`. 

然後

type.GetType() - this gives `System.Type` 
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type` 

由於@PeterRitchie正確地指出,在這一點上你的代碼是找物業LabelSystem.Type。該屬性不存在。

的溶液或者是

一個)提供的MyClass一個實例到延伸:

var myInstance = new MyClass() 
myInstance.HasProperty("Label") 

b)將所述延伸上System.Type

public static bool HasProperty(this Type obj, string propertyName) 
{ 
    return obj.GetProperty(propertyName) != null; 
} 

typeof(MyClass).HasProperty("Label"); 
+2

即您的代碼正在尋找'Type.Label',而不是'MyClass.Label'。 – 2013-03-11 14:40:49

+0

如何將這個擴展名System.Type放在哪裏可以找到/。這代碼在哪裏執行? – Demodave 2015-03-20 14:43:01

+1

@Demodave - 擴展方法只是在一個公共靜態類中。請參閱這裏獲取更多信息:https://msdn.microsoft.com/en-GB/library/bb383977.aspx – Jamiec 2015-03-20 14:48:06

2

有兩種可能性。

您確實沒有Label屬性。

您需要調用適當的GetProperty overload並傳遞正確的綁定標誌,例如, BindingFlags.Public | BindingFlags.Instance

如果您的財產不公開,您將需要使用BindingFlags.NonPublic或其他符合您的用例的標誌組合。閱讀引用的API文檔以查找詳細信息。

編輯:

哎呀,剛纔注意到你typeof(MyClass)調用GetPropertytypeof(MyClass)Type這肯定沒有Label財產。

+0

使用的默認綁定標誌是'Instance | Public | Static',iirc。 – LukeH 2013-03-11 14:34:35

+0

@LukeH,我不確定,所以我寫了'正確'並且加上'例如':)也許'Label'是私人財產。 – 2013-03-11 14:39:05

10

這回答了一個不同的問題,但希望這可以幫助有人閱讀此問題。我正在尋找一個稍微不同的問題,這是我的解決方案:

如果想弄清楚如果一個對象(而不是類)有一個屬性,

OBJECT.GetType().GetProperty("PROPERTY") != null 

返回true,如果(但不僅當)財產存在。

在我的情況,我在一個ASP.NET MVC的部分視圖,並希望渲染的東西,如果該屬性不存在,或屬性(布爾)爲真。

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) || 
     Model.AddTimeoffBlackouts) 

幫我在這裏。

+0

正是我所需要的,感謝張貼這! – Rob 2017-10-20 12:09:35

0

如果您有約束力,好像我是:

<%# Container.DataItem.GetType().GetProperty("Property1") != null ? DataBinder.Eval(Container.DataItem, "Property1") : DataBinder.Eval(Container.DataItem, "Property2") %> 
0

我得到這個錯誤:「類型不包含定義的getProperty」搭售接受的答案的時候。

這是我結束了:

using System.Reflection; 

if (productModel.GetType().GetTypeInfo().GetDeclaredProperty(propertyName) != null) 
{ 

}