Dan*_*ler 3 c# reflection properties propertyinfo
出于某些原因,我需要创建一个PropertyInfo
与某些类属性相对应的实例字典(让我们调用它EntityClass
).
好的,我可以用typeof(EntityClass).GetProperties()
.
但我还需要确定某些特定属性的值(在编译时已知).通常我可以做以下其中一项:
EntityInstance.PropertyX = Value;
typeof(EntityClass).GetProperty("PropertyX").SetValue(EntityInstance, Value, null);
Run Code Online (Sandbox Code Playgroud)
为了填满我的字典,我需要使用PropertyInfo
实例而不是正常设置值.但我觉得通过字符串名称获取属性并不舒服.如果某些EntityClass发生更改,则会带来许多异常而不是编译错误.所以,我要问的是:
如何在不传递字符串名称的情况下获取已知属性的PropertyInfo?如果有像代表一样的东西,我会很高兴:
SomeDelegateType MyDelegate = EntityInstance.MethodX;
Run Code Online (Sandbox Code Playgroud)
理想的情况是:
SomePropertyDelegate MyPropertyDelegate = EntityInstance.PropertyX;
Run Code Online (Sandbox Code Playgroud)
像这样的东西?
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;
}
Run Code Online (Sandbox Code Playgroud)
要么
public PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> lambda)
{
var member = lambda.Body as MemberExpression;
return member.Member as PropertyInfo;
}
Run Code Online (Sandbox Code Playgroud)
public class User
{
public string Name { set; get; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4436 次 |
最近记录: |