获取的类型和原因的属性值 - 物业自定义属性 [英] Custom attribute on property - Getting type and value of attributed property

查看:118
本文介绍了获取的类型和原因的属性值 - 物业自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于获取的类型和原因的属性值 - 物业自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆