使用属性名称调用属性或方法

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而不是属性或方法名称来调用这两个属性或方法?

Ani*_*Ani 5

方法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)

  • Robert:可能你已经有了一个`CodeNameAttribute`类,否则你将无法执行`[CodeName("foo")]`因为这实际上会导致`CodeNameAttribute`对象的实例化. (2认同)