且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向类的每个属性添加其他属性

更新时间:2023-12-02 21:00:10

您可以在属性中添加所需的自定义属性,然后在对象上使用扩展方法来访问这些属性.

You could add a custom attribute that you want to the property and then use an extension method on object to access those attributes.

类似的事情应该起作用

首先,您需要创建属性类

First you will need to create your attribute class

[AttributeUsage(AttributeTargets.All/*, AllowMultiple = true*/)]
public class WarningAttribute : System.attribute
{
   public readonly string Warning;

   public WarningAttribute(string warning)
   {
      this.Warning = warning;
   }    
}

更多阅读此处

按原样使用

[WarningAttribute("Warning String")]
public string A {get;set;}

然后按 MSDN文章

public static string Warning(this Object object) 
{
    System.Attribute[] attrs = System.Attribute.GetCustomAttributes(object);

    foreach (System.Attribute attr in attrs)
        {
            if (attr is WarningAttrbiute)
            {
                return (WarningAttribute)attr.Warning;
            }
        } 
}

然后,如果您有想要访问警告的项目,只需致电

Then if you have an item that you want to access the warning on you can simply call

test.A.Warning;

如果您想设置警告字符串,则可以更干净地实现某种设置方法.可能通过设置辅助对象或属性类型来实现.

If you're wanting to set the warning string you could implement some kind of setter for that a little more cleanly. Potentially through setting a secondary object or property type.

执行此操作的另一种方法是,不仅可以使用stringobject,还可以创建一个自定义的泛型类型来处理该属性设置.

An alternative method to do this would be instead of just using string and object you could create a custom generic type to handle that property setting.

类似

public class ValidationType<T>
{
   public T Value {get; set;}
   public string Warning {get; set;}
   public string Error {get; set;}

   public ValidationType(T value)
   {
      Value = value;
   }
}

使用方式

var newWarning = new ValidationType<string>("Test Type");
newWarning.Warning = "Test STring";
Console.WriteLine("newWarning.Value");