C#通过属性名称动态访问属性值
发布时间:2020-12-15 17:50:09 所属栏目:百科 来源:网络整理
导读:我想要解决的问题是如何编写一个以属性名称作为字符串的方法,并返回分配给该属性的值. 我的模型类被声明类似于: public class Foo{ public int FooId public int param1 public double param2} 从我的方法,我想做一些类似的事情 var property = GetProperty
我想要解决的问题是如何编写一个以属性名称作为字符串的方法,并返回分配给该属性的值.
我的模型类被声明类似于: public class Foo { public int FooId public int param1 public double param2 } 从我的方法,我想做一些类似的事情 var property = GetProperty("param1) var property2 = GetProperty("param2") 我正在尝试通过使用表达式来做到这一点 public dynamic GetProperty(string _propertyName) { var currentVariables = m_context.Foo.OrderByDescending(x => x.FooId).FirstOrDefault(); var parameter = Expression.Parameter(typeof(Foo),"Foo"); var property = Expression.Property(parameter,_propertyName); var lambda = Expression.Lambda<Func<GlobalVariableSet,bool>>(parameter); } 这种方法是否正确,如果是这样,是否可以将其作为动态类型返回? 答案是正确的,使得这太复杂了.解决方案现在是: public dynamic GetProperty(string _propertyName) { var currentVariables = m_context.Foo.OrderByDescending(g => g.FooId).FirstOrDefault(); return currentVariables.GetType().GetProperty(_propertyName).GetValue(currentVariables,null); } 解决方法public static object ReflectPropertyValue(object source,string property) { return source.GetType().GetProperty(property).GetValue(source,null); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |