在C#中的自定义属性内添加属性 [英] Add attributes inside custom attribute in c#
问题描述
我想动态地将属性添加到给定类的属性中,因为项目会变得越来越大,并且过程完全是重复的,就像这样:
I want to dynamically add attributes to properties of a given class, because the project will get bigger and the procedure is totally repeatinglly, something like so :
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;}
}
当然,上面的代码不是真正的程序,但是我试图使其变得简单.
of course the code above is not a real program, but I tried to make it simple.
是否可以这样做?否则,是否有解决方法?
Is it possible to do this? or if not, is there a workaround?
更新:我知道有一个名为 CallerMemberName
的属性,该属性可检索给定属性的名称,但是如何获取属性本身并为其添加更多属性呢?>
Update: I know there's an attribute called CallerMemberName
that retrieves name of a given property, but how to get the property itself and add more attributes to it?
推荐答案
我认为您可能可以结合其他帖子的以下答案来做一些工作.
I think you might be able to make something work combining the below answers from other posts.
通过属性访问对象属性:可以使用C#属性访问目标类别?
Access object properties from Attribute: Can C# Attributes access the Target Class?
在运行时添加属性:如何通过在运行时创建新类型在运行时向属性添加属性.
除非您要对所有属性进行定期更改,否则最好先处理重复的工作.像这样全盘进行工作时,不可避免地会存在风险/问题.
Unless you're going to be making regular changes across all the properties it may just be better to deal with the repetitive work up front. There are inevitably risks/issues down the road when doing stuff across the board like this.
这篇关于在C#中的自定义属性内添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!