从对象获取属性信息不给属性名作为字符串 [英] Get Property Info from an object without giving the property name as string

查看:183
本文介绍了从对象获取属性信息不给属性名作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一些原因,我需要建立相应的一些类的属性(我们称之为的PropertyInfo 实例的字典 EntityClass )。



好吧,我可以使用 typeof运算(entityClass)方法.GetProperties()



但我还需要确定某些特定属性的值(在编译时已知)。
通常我可以做下列之一:

  EntityInstance.PropertyX =值; 
typeof运算(entityClass)方法.GetProperty(PropertyX)的SetValue(EntityInstance,值null)。

为了填补我的字典里,我需要使用的PropertyInfo 实例,而不仅仅是通常设定值。但我不觉得其字符串名称舒适获取属性。如果某些EntityClass变化,这会带来许多例外,而不是编译错误。所以,我想问的是:



如何获得一个知名物业公司的PropertyInfo没有通过字符串名称?
如果有什么东西,就像代表我会爱:

  SomeDelegateType MyDelegate = EntityInstance.MethodX; 



在理想情况下:

  SomePropertyDelegate MyPropertyDelegate = EntityInstance.PropertyX; 


解决方案

这样呢?



 字符串s = getPropertyName方法<使用者>(X => x.Name); 

公共字符串getPropertyName方法< T>(表达式来; Func键< T,对象>>拉姆达)
{
VAR成员= lambda.Body为MemberExpression;
VAR道具= member.Member为的PropertyInfo;
返回prop.Name;
}

 公开的PropertyInfo为getPropertyInfo< T>(表达式来; Func键< T,对象>>拉姆达)
{
VAR成员= lambda.Body为MemberExpression;
返回member.Member为的PropertyInfo;
}






 公共类用户
{
公共字符串名称{设置;得到; }
}


For some reasons, I need to create a Dictionary of PropertyInfo instances corresponding to some class' properties (let's call it EntityClass).

Ok, I could use typeof(EntityClass).GetProperties().

But I also need to determine a value for some specific properties (known at compile time). Normally I could do one of the following:

EntityInstance.PropertyX = Value;
typeof(EntityClass).GetProperty("PropertyX").SetValue(EntityInstance, Value, null);

In order to fill up my dictionary, I need to use PropertyInfo instances instead of just setting the values normally. But I don't feel confortable getting properties by their string names. If some EntityClass changes, it would bring many exceptions instead of compile errors. So, what I ask is:

How to get a known property's PropertyInfo without passing the string name? I would love if there's something just like delegates:

SomeDelegateType MyDelegate = EntityInstance.MethodX;

Ideally:

SomePropertyDelegate MyPropertyDelegate = EntityInstance.PropertyX;

解决方案

Something like this?

string s = GetPropertyName<User>( x=> x.Name );

public string GetPropertyName<T>(Expression<Func<T, object>> lambda)
{
    var member = lambda.Body as MemberExpression;
    var prop = member.Member as PropertyInfo;
    return prop.Name;
}

or

public PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> lambda)
{
    var member = lambda.Body as MemberExpression;
    return member.Member as PropertyInfo;
}


public class User
{
    public string Name { set; get; }
}

这篇关于从对象获取属性信息不给属性名作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆