你可以得到合并的属性一类在C#中? [英] Can you get merged attributes for a class in C#?

查看:122
本文介绍了你可以得到合并的属性一类在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有类下面的一组,是有可能DerivedClass的属性要合并?目前,如果我使用的GetType()。GetCustomAttributes()方法来传递真正的继承花费最高属性的继承结构。

即。 [另一个(鲍勃)]和[我的(16)]

是否有可能为属性要合并?所以,我结束了两个属性[我的(16,男)]和[另一个(鲍勃)]

我的意思不是说,我将指定的[我的(16,男)的属性,而是我将返回与16的年龄与男性的性别属性。

 公共类MyAttribute:属性
{

    公共MyAttribute(INT岁)
    {
        年龄=岁;
    }

    公共MyAttribute(INT年龄,性别的字符串)
    {
        年龄=岁;
        性别=性别;
    }

    公众诠释年龄{获得;组; }

    公共字符串性别{获得;组; }

}

公共类AnotherAttribute:属性
{

    公共AnotherAttribute(字符串名称)
    {
        名称=名称;
    }

    公共字符串名称{;组; }

}

[我的(12,男)
[另一个(鲍勃)
公共类BaseClass的
{
}

[我(16)
公共类DerivedClass:BaseClass的
{
}
 

解决方案

您可以有相同属性的多个实例在一个实体(这是一个选项 AttributeUsageAttribute特性适用于你的属性)。当你的属性的类型,你可以得到所有应用到继承链的属性。

不过没有什么标准的工具,将采取两种属性的情况下,使之一。

(理论上的后处理器重新写了MSIL能做到这一点。)

Say I have the following set of classes, is it possible for the attributes of DerivedClass to be merged? Currently if I use the GetType().GetCustomAttributes()method passing in true for inheritance it takes the highest attributes in the inheritance structure.

i.e. [Another("Bob")] and [My(16)]

Is it possible for the attributes to be merged? So I would end up with two attributes of [My(16, "Male")] and [Another("Bob")]

I don't mean to say that I would specify an attribute of [My(16, "Male")] but rather I would be returned an attribute with an Age of 16 and a Gender of Male.

public class MyAttribute : Attribute
{

    public MyAttribute(int age)
    {
        Age = age;
    }

    public MyAttribute(int age, string gender)
    {
        Age = age;
        Gender = gender;
    }

    public int Age { get; set; }

    public string Gender { get; set; }

}

public class AnotherAttribute : Attribute
{

    public AnotherAttribute(string name)
    {
        Name = name;
    }

    public string Name { get; set; }

}

[My(12, "Male")]
[Another("Bob")]
public class BaseClass
{
}

[My(16)]
public class DerivedClass : BaseClass
{
}

解决方案

You can have multiple instances of the same attribute on an entity (this is an option on the AttributeUsageAttribute applied to your attribute). When you get attributes on a type, you can get all the attributes applied to the inheritance chain.

However there is nothing in the standard tools that will take two attribute instances and make one.

(In theory a post processor that re-wrote the MSIL could do this.)

这篇关于你可以得到合并的属性一类在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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