在c#的自定义属性内添加属性

问题描述 投票:0回答:1

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

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的属性可以检索给定属性的名称,但是如何获取属性本身并向其中添加更多属性呢?

c# .net asp.net-mvc custom-attributes dynamic-attributes
1个回答
1
投票

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

从属性访问对象属性:Can C# Attributes access the Target Class?

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

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

© www.soinside.com 2019 - 2024. All rights reserved.