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

uhu*_*uhu 19 .net c#

我有一个类型为" object " 的对象(.NET).我不知道运行时它背后的" 真实类型(类) ",但我知道,该对象有一个属性" 字符串名称 ".我怎样才能追溯"名字"的价值?这可能吗?

这样的事情:

object item = AnyFunction(....);
string value = item.name;
Run Code Online (Sandbox Code Playgroud)

Ere*_*mez 45

您可以使用dynamic而不是object:

dynamic item = AnyFunction(....);
string value = item.name;
Run Code Online (Sandbox Code Playgroud)


Waq*_*qar 42

使用反射

System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");
String name = (String)(pi.GetValue(item, null));
Run Code Online (Sandbox Code Playgroud)


Maa*_*ten 5

反思可以帮助你。

var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
Run Code Online (Sandbox Code Playgroud)


Raf*_*fal 5

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

  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);
Run Code Online (Sandbox Code Playgroud)

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