簡體   English   中英

在不知道背后類的情況下獲取 C# 中特定對象屬性的值

[英]Get value of a specific object property in C# without knowing the class behind

我有一個“對象”類型的對象(.NET)。 在運行時我不知道它背后的“真實類型(類) ”,但我知道,該對象有一個屬性“字符串名稱”。 我怎樣才能取回“名字”的價值? 這可能嗎?

是這樣的:

object item = AnyFunction(....);
string value = item.name;

使用反射

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));

您可以使用dynamic而不是object來做到這一點:

dynamic item = AnyFunction(....);
string value = item.name;

請注意, 動態語言運行時(DLR) 具有內置緩存機制,因此后續調用非常快。

反思可以幫助你。

var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);

反射和動態值訪問是這個問題的正確解決方案,但速度很慢。 如果你想要更快的東西,那么你可以使用表達式創建動態方法:

  object value = GetValue();
  string propertyName = "MyProperty";

  var parameter = Expression.Parameter(typeof(object));
  var cast = Expression.Convert(parameter, value.GetType());
  var propertyGetter = Expression.Property(cast, propertyName);
  var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing

  var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();

 var retrivedPropertyValue = propertyRetriver(value);

如果您緩存創建的函數,這種方式會更快。 例如在字典中,假設屬性名稱未更改或類型和屬性名稱的某種組合,鍵將是對象的實際類型。

您可以使用動態而不是對象來做到這一點:

dynamic item = AnyFunction(....);
string value = item["name"].Value;

在某些情況下,反射無法正常工作。

如果所有項目類型都相同,您可以使用字典。 例如,如果您的項目是字符串:

Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(item);

或整數:

Dictionary<string, int> response = JsonConvert.DeserializeObject<Dictionary<string, int>>(item);

簡單地為一個對象的所有屬性嘗試這個,

foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
   var propertyName = prop.Name;
   var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);

   //Debug.Print(prop.Name);
   //Debug.Print(Functions.convertNullableToString(propertyValue));

   Debug.Print(string.Format("Property Name={0} , Value={1}", prop.Name, Functions.convertNullableToString(propertyValue)));
}

注意: Functions.convertNullableToString()是自定義函數,用於將 NULL 值轉換為 string.empty。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM