Custom Attributes on Class Members

后端 未结 2 1842
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 12:20

I am using a Custom Attribute to define how a class\'s members are mapped to properties for posting as a form post (Payment Gateway). I have the custom attribute working ju

2条回答
  •  礼貌的吻别
    2020-12-30 12:52

    You can't really do this, unless you're using C# 3.0 in which case you'll need to rely on LINQ (ehm, expression trees).

    What you do is that you create a dummy method for a lambda expression which lets the compiler generate the expression tree (compiler does the type checking). Then you dig into that tree to get the member. Like so:

    static FieldInfo GetField(
        Expression> accessor)
    {
        var member = accessor.Body as MemberExpression;
        if (member != null)
        {
            return member.Member as FieldInfo;
        }
        return null; // or throw exception...
    }
    

    Given the following class:

    class MyClass
    {
        public int a;
    }
    

    You can get the meta data like this:

    // get FieldInfo of member 'a' in class 'MyClass'
    var f = GetField((MyClass c) => c.a); 
    

    With a reference to that field you can then dig up any attribute the usual way. i.e. reflection.

    static TAttribute GetAttribute( 
        this MemberInfo member ) where TAttribute: Attribute
    {
        return member.GetCustomAttributes( typeof( TAttribute ), false )
            .Cast().FirstOrDefault();
    }
    

    Now you can dig up an attribute on any field by something which is in large checked by the compiler. It also works with refactoring, if you rename 'a' Visual Studio will catch that.

    var attr = GetField((MyClass c) => c.a).GetAttribute();
    Console.WriteLine(attr.DisplayName);
    

    There's not a single literal string in that code there.

提交回复
热议问题