在不知道背后的类的情况下获取 C# 中特定对象属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11395315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:42:28  来源:igfitidea点击:

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

c#.net

提问by uhu

I have an object (.NET) of type "object". I don't know the "real type (class)" behind it during runtime , but I know, that the object has a property "string name". How can I retrive the value of "name"? Is this possible?

我有一个“对象”类型的对象(.NET)。我不知道运行时它背后的“真实类型(类)”,但我知道,该对象有一个属性“字符串名称”。如何检索“名称”的值?这可能吗?

something like this:

像这样:

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

采纳答案by Waqar

Use reflection

使用反射

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

回答by Eren Ers?nmez

You can do it using dynamicinstead of object:

您可以使用dynamic代替object

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

回答by Maarten

Reflection can help you.

反思可以帮助你。

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

回答by Rafal

Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:

反射和动态值访问是这个问题的正确解决方案,但速度很慢。如果你想要更快的东西,那么你可以使用表达式创建动态方法:

  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);

This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.

如果缓存创建的函数,这种方式会更快。例如在字典中,假设属性名称没有改变或类型和属性名称的某种组合,键将是对象的实际类型。

回答by Haseeb Ahmed

Simply try this for all properties of an object,

只需为对象的所有属性尝试此操作,

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)));
}

NOTE: Functions.convertNullableToString()is custom function using for convert NULL value into string.empty.

注意:Functions.convertNullableToString()是用于将 NULL 值转换为 string.empty 的自定义函数。

回答by Dugh

In some cases, Reflection doesn't work properly.

在某些情况下,反射无法正常工作。

You could use dictionaries, if all item types are the same. For instance, if your items are strings :

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

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

Or ints:

或整数:

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