在C#中的自定义属性内添加属性

时间:2020-03-20 20:51:36

标签: c# .net asp.net-mvc custom-attributes dynamic-attributes

我想动态地将属性添加到给定类的属性中,因为项目会变得越来越大,并且过程完全是重复的,就像这样:

public class MyAttr : Attribute {
    public MyAttr () {
        foreach(var prop in properties) {
            prop.Attributes.Add([Display(Name =  nameof(prop.Name), ResourceType = typeof(Labels))]);            
        }
    }
}

并在类上使用它:

[MyAttr]
public class SomeClass {
    public string Name {get; set;}
    public string Description {get; set;}
}

当然,上面的代码不是真正的程序,但是我试图使其变得简单。

是否可以这样做?否则,是否有解决方法?

更新:我知道有一个名为CallerMemberName的属性可以检索给定属性的名称,但是如何获取属性本身并为其添加更多属性呢?

1 个答案:

答案 0 :(得分:2)

我认为您可能可以结合其他帖子的以下答案来使工作成功。

通过属性Can C# Attributes access the Target Class?

访问对象属性

在运行时添加属性:How to add an attribute to a property at runtime,通过在运行时创建新类型。

除非您要对所有属性进行定期更改,否则最好先处理重复的工作。像这样全盘进行工作时,不可避免地会有风险/问题。

相关问题