[英]Is it possible in c# to get the attributes attached to a property from within the instance of that property, without knowing the containing class?
[英]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));
反思可以帮助你。
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.