你能在 C# 中获得一个类的合并属性吗?

Can you get merged attributes for a class in C#?(你能在 C# 中获得一个类的合并属性吗?)
本文介绍了你能在 C# 中获得一个类的合并属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下一组类,是否可以合并 DerivedClass 的属性?目前,如果我使用传递 true 的 GetType().GetCustomAttributes() 方法进行继承,它将采用继承结构中的最高属性.

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.

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

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

属性可以合并吗?所以我最终会得到两个属性 [My(16, "Male")] 和 [Another("Bob")]

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

我并不是说我会指定一个属性为 [My(16, "Male")],而是我会返回一个年龄为 16 岁且性别为男性的属性.

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

推荐答案

您可以在一个实体上拥有同一属性的多个实例(这是应用于您的属性的 AttributeUsageAttribute 上的一个选项).当你获取一个类型的属性时,你可以获取应用到继承链的所有属性.

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.

(理论上,重写 MSIL 的后处理器可以做到这一点.)

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

这篇关于你能在 C# 中获得一个类的合并属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)