.net 属性的自定义属性-获取属性化属性的类型和值

w51jfk4q  于 2023-08-08  发布在  .NET
关注(0)|答案(5)|浏览(131)

我有以下自定义属性,可以应用于属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class IdentifierAttribute : Attribute
{
}

字符串
举例来说:

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

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


还有其他类,Identifier属性可以添加到不同类型的属性中:

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

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

    public string SomeOtherProperty { get; set; }
}


然后,我需要能够在我的消费类中获得这些信息。举例来说:

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


最好的办法是什么?我需要获取[Identifier()]字段的类型(int、string等...)和实际值,显然基于类型。

kupeojn6

kupeojn61#

类似于下面的,,这将只使用它经过的第一个属性,它有属性,当然你可以把它放在多个。

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;
    }

字符串

tkclm6bt

tkclm6bt2#

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)
    }
}

字符串

v09wglhw

v09wglhw3#

有点晚了,但这里是我为枚举(也可以是任何对象)做的一些事情,并使用扩展获取description属性值(这可以是任何属性的泛型):

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

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

    ...
}

字符串
获取值:

var code = TransactionTypeEnum.DROP.ToCode();


支持我所有枚举的扩展:

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;
}

bq8i3lrv

bq8i3lrv4#

示例

我用一个属性acceptances参数和works一个属性扩展了您的示例

[AttributeUsage(AttributeTargets.Property,AllowMultiple = true)]
public class PersonAttribute : Attribute
{
    public readonly string FieldName;
    public readonly string FieldType;
    public PersonAttribute(string name,string type)
    {
        FieldName = name;
        FieldType = type;
    }    
}

字符串
该属性应用于Person类上的,如下所示:

public class Person
{
    public string FirstName {get;set;} = "FirstName";
    public string LastName {get;set;} = "LastName";
    
    [Person("addressline1","db")]
    [Person("new_address1","system")]
    public string AddressLine1 {get;set;} = "Banglore";
    
    [Person("addressline2","system")]
    public string AddressLine2 {get;set;} = "Karnataka";
    
    [Person("addressline3","dto")]
    public string AddressLine3 {get;set;} = "INDIA";    
}

溶液

我已经创建了下面的扩展函数,它是通用的,能够从类中读取所有属性和属性值。

public static class AttributesExt
{
    public static IEnumerable<PropertyInfo> AllAttributes<T>(this object obj,string name)
    {
        var allProperties = obj.GetType().GetProperties()
        .Where(_ => _.GetCustomAttributes(typeof(T), true).Length >= 1  && _.Name == name);
        return allProperties;
    }
    
    public static IEnumerable<PropertyInfo> AllAttributes<T>(this object obj)
    {
        var allProperties = obj.GetType().GetProperties()
        .Where(_ => _.GetCustomAttributes(typeof(T), true).Length >= 1);
        return allProperties;
    }

    public static T ReadAttribute<T>(this PropertyInfo propertyInfo)
    {
        var returnType = propertyInfo.GetCustomAttributes(typeof(T), true)
        .Cast<T>().FirstOrDefault();
        return returnType;
    }
}


现在在main方法中,如果我们写

void Main()
{
    Person p = new Person();
    
    var all = p.AllAttributes<PersonAttribute>().Dump(); //Get All custom attributes
    p.AllAttributes<PersonAttribute>("AddressLine3").Dump();
    all.First(_=> _.Name == "AddressLine2").ReadAttribute<PersonAttribute>().Dump();
    all.First(_=> _.Name == "AddressLine2").ReadAttribute<PersonAttribute>().FieldName.Dump();
}


我们可以按照下面的截图读取这些值。


的数据

ig9co6j1

ig9co6j15#

这里有一个更真实的例子。我们使用扩展方法并检查属性是否包含FieldMetaDataAttribute(源代码库中的一个自定义属性),该属性具有有效的Major和MinorVersion。一般感兴趣的是我们使用父类类型和GetProperties并检索PropertyInfo,然后在这种特殊情况下使用GetCustomAttribute检索属性FieldMetaDataAttribute的部分。使用这段代码启发如何更通用地检索自定义属性。当然,这可以被完善,以形成一个通用的方法来检索类示例的任何属性的给定属性。

/// <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;
    }

字符串

相关问题