Get Property Info from an object without giving the property name as string

雨燕双飞 提交于 2019-12-21 19:56:56

问题


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;

回答1:


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



回答2:


Not sure what you need but may be it helps you move on.

public class Property<TObj, TProp>
{
    private readonly TObj _instance;
    private readonly PropertyInfo _propInf;

    public Property(TObj o, Expression<Func<TObj, TProp>> expression)
    {
        _propInf = ((PropertyInfo)((MemberExpression)expression.Body).Member);
        _instance = o;
    }

    public TProp Value
    {
        get
        {
            return (TProp)_propInf.GetValue(_instance);
        }
        set
        {
            _propInf.SetValue(_instance, value);
        }
    }
}

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

var user = new User();
var name = new Property<User, string>(user, u => u.Name);
name.Value = "Mehmet";
Console.WriteLine(name.Value == user.Name); // Prints True


来源:https://stackoverflow.com/questions/16777292/get-property-info-from-an-object-without-giving-the-property-name-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!