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

编程入门 行业动态 更新时间:2024-10-15 22:28:55
本文介绍了在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#中的自定义属性内添加属性

本文发布于:2023-11-17 00:11:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608094.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   自定义

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!