[英]How to get a property value using reflection
我有以下代碼:
FieldInfo[] fieldInfos;
fieldInfos = GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
我想要做的是使用反射在運行時獲取當前實例化實例的一個屬性的值。 我怎樣才能做到這一點?
這樣的事情應該有效:
var value = (string)GetType().GetProperty("SomeProperty").GetValue(this, null);
嘗試使用GetProperties方法,它應該為您提供屬性,而不是字段。
要檢索值,請執行以下操作:
object foo = ...;
object propertyValue = foo.GetType().GetProperty("PropertyName").GetValue(foo, null);
這是使用GetProperty,它只返回一個PropertyInfo對象,而不是它們的數組。 然后我們調用GetValue,它接受對象的參數來從中檢索值(PropertyInfo特定於類型,而不是實例)。 GetValue的第二個參數是一個索引器數組,用於索引屬性,我假設您感興趣的屬性不是索引屬性。 (索引屬性是允許您執行list[14]
以檢索列表的第14個元素。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.