问题
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