开发者

Custom attribute on property - Getting type and value of attributed property

开发者 https://www.devze.com 2023-01-08 05:34 出处:网络
I have the following custom attribute, which can be applied on properties: [AttributeUsage(AttributeTargets.开发者_Go百科Property, AllowMultiple = false)]

I have the following custom attribute, which can be applied on properties:

[AttributeUsage(AttributeTargets.开发者_Go百科Property, AllowMultiple = false)]
public class IdentifierAttribute : Attribute
{
}

For example:

public class MyClass
{
    [Identifier()]
    public string Name { get; set; }

    public int SomeNumber { get; set; }
    public string SomeOtherProperty { get; set; }
}

There will also be other classes, to which the Identifier attribute could be added to properties of different type:

public class MyOtherClass
{
    public string Name { get; set; }

    [Identifier()]
    public int SomeNumber { get; set; }

    public string SomeOtherProperty { get; set; }
}

I then need to be able to get this information in my consuming class. For example:

public class TestClass<T>
{
    public void GetIDForPassedInObject(T obj)
    {
        var type = obj.GetType();
        //type.GetCustomAttributes(true)???
    }
}

What's the best way of going about this? I need to get the type of the [Identifier()] field (int, string, etc...) and the actual value, obviously based on the type.


Something like the following,, this will use only the first property it comes accross that has the attribute, of course you could place it on more than one..

    public object GetIDForPassedInObject(T obj)
    {
        var prop = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                   .FirstOrDefault(p => p.GetCustomAttributes(typeof(IdentifierAttribute), false).Count() ==1);
        object ret = prop !=null ?  prop.GetValue(obj, null) : null;

        return ret;
    }  


public class TestClass<T>
{
    public void GetIDForPassedInObject(T obj)
    {
        PropertyInfo[] properties =
            obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);            

        PropertyInfo IdProperty = (from PropertyInfo property in properties
                           where property.GetCustomAttributes(typeof(Identifier), true).Length > 0
                           select property).First();

         if(null == IdProperty)
             throw new ArgumentException("obj does not have Identifier.");

         Object propValue = IdProperty.GetValue(entity, null)
    }
}


A bit late but here is something I did for enums (could be any object also) and getting the description attribute value using an extension (this could be a generic for any attribute):

public enum TransactionTypeEnum
{
    [Description("Text here!")]
    DROP = 1,

    [Description("More text here!")]
    PICKUP = 2,

    ...
}

Getting the value:

var code = TransactionTypeEnum.DROP.ToCode();

Extension supporting all my enums:

public static string ToCode(this TransactionTypeEnum val)
{
    return GetCode(val);
}

public static string ToCode(this DockStatusEnum val)
{
    return GetCode(val);
}

public static string ToCode(this TrailerStatusEnum val)
{
    return GetCode(val);
}

public static string ToCode(this DockTrailerStatusEnum val)
{
    return GetCode(val);
}

public static string ToCode(this EncodingType val)
{
    return GetCode(val);
}

private static string GetCode(object val)
{
    var attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);

    return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}


Here is a more real-word example. We use an extension method and check if a property contains a FieldMetaDataAttribute (a custom attribute in my source code base) with valid Major and MinorVersion. What is of general interest is the part where we use the parent class type and GetProperties and retrieve the ProperyInfo and then use GetCustomAttribute to retrieve a attribute FieldMetaDataAttribute in this special case. Use this code for inspiration how to do more generic way of retrieving a custom attribute. This can of course be polished to make a general method to retrieve a given attribute of any property of a class instance.

        /// <summary>
    /// Executes the action if not the field is deprecated 
    /// </summary>
    /// <typeparam name="TProperty"></typeparam>
    /// <typeparam name="TForm"></typeparam>
    /// <param name="form"></param>
    /// <param name="memberExpression"></param>
    /// <param name="actionToPerform"></param>
    /// <returns>True if the action was performed</returns>
    public static bool ExecuteActionIfNotDeprecated<TForm, TProperty>(this TForm form, Expression<Func<TForm, TProperty>> memberExpression, Action actionToPerform)
    {
        var memberExpressionConverted = memberExpression.Body as MemberExpression;
        if (memberExpressionConverted == null)
            return false; 

        string memberName = memberExpressionConverted.Member.Name;


        PropertyInfo matchingProperty = typeof(TForm).GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .FirstOrDefault(p => p.Name == memberName);
        if (matchingProperty == null)
            return false; //should not occur

        var fieldMeta = matchingProperty.GetCustomAttribute(typeof(FieldMetadataAttribute), true) as FieldMetadataAttribute;
        if (fieldMeta == null)
        {
            actionToPerform();
            return true;
        }

        var formConverted = form as FormDataContract;
        if (formConverted == null)
            return false;

        if (fieldMeta.DeprecatedFromMajorVersion > 0 && formConverted.MajorVersion > fieldMeta.DeprecatedFromMajorVersion)
        {
            //major version of formConverted is deprecated for this field - do not execute action
            return false;
        }

        if (fieldMeta.DeprecatedFromMinorVersion > 0 && fieldMeta.DeprecatedFromMajorVersion > 0
                                                     && formConverted.MinorVersion >= fieldMeta.DeprecatedFromMinorVersion
                                                     && formConverted.MajorVersion >= fieldMeta.DeprecatedFromMajorVersion)
            return false; //the field is expired - do not invoke action 
        actionToPerform();
        return true;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消