获取的类型和原因的属性值 - 物业自定义属性属性、自定义、物业、原因

2023-09-02 20:49:02 作者:一尘不染美少年

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

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

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

也将有其他类中,向其中标识符属性可以被添加到不同类型的属性:

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