Rob*_*vey 4 c# reflection methods attributes properties
假设我有一个看起来像这样的类:
public class CallByAttribute
{
[CodeName("Foo")]
public string MyProperty { get; set; }
[CodeName("Bar")]
public string MyMethod(int someParameter)
{
return myDictionary[someParameter];
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用CodeName而不是属性或方法名称来调用这两个属性或方法?
方法1:
public static TOutput GetPropertyByCodeName<TOutput>(this object obj, string codeName)
{
var property = obj.GetType()
.GetProperties()
.Where(p => p.IsDefined(typeof(CodeNameAttribute), false))
.Single(p => ((CodeNameAttribute)(p.GetCustomAttributes(typeof(CodeNameAttribute), false).First())).Name == codeName);
return (TOutput)property.GetValue(obj, null);
}
Run Code Online (Sandbox Code Playgroud)
注意:如果指定的属性不存在,codeName
或者多个属性共享相同属性,则抛出此属性codeName
.
用法:
CallByAttribute obj= ...
string myProperty = obj.GetPropertyByCodeName<string>("Foo");
Run Code Online (Sandbox Code Playgroud)
方法2:
如果您使用的是C#4,则可以编写自己的System.Dynamic.DynamicObject
可以将动态调用路由到正确的成员.
这将允许更清晰的语法.例如,您应该能够完成允许的事情:
CallByAttribute obj= ...
dynamic objectByCodeName = new ObjectByCodeName(obj);
objectByCodeName.Foo = "8";
objectByCodeName.Bar();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6211 次 |
最近记录: |