在dotnet/.NET中实现自定义属性的最佳方法是什么?

IAm*_*00B 9 .net c# attributes

我真的不懂属性.我已经阅读了各种各样的书籍和帖子,但我只是不明白.

由于我不理解它们,我也不明白如何有效地使用它们.

1)你能给我一个很好的定义属性是什么以及它用于什么?

2)你能在C#中给我一个如何制作和使用自定义属性的好代码示例吗?

And*_*are 11

我可以给你一个例子,但与这篇好文章相比,它会变得苍白:

在C#中定义和使用自定义属性类

企业期望从现代软件开发人员那里获得的复杂的组件式开发需要比过去的设计方法更大的设计灵活性.Microsoft的.NET Framework广泛使用属性,通过所谓的"声明性"编程提供附加功能.属性增强了软件系统的灵活性,因为它们促进了功能的松散耦合.因为您可以创建自己的自定义属性类然后对它们进行操作,所以您可以利用属性的松散耦合功能来实现自己的目的.


cjk*_*cjk 9

假设您有一个具有一系列属性的类,您将使用反射来完成这些属性.任何字符串都可能需要验证,以检查它们是否不超过一定数量.

然后TextLength,您可以使用默认的整数构造函数和整数属性/字段创建属性.然后,您可以在类中的每个字符串属性上读取属性,并将属性值的长度与属性中指定的数字进行比较.

码:

public class TextLengthAttribute : Attribute
{
    private int length;
    public int Length { get { return length; } set { length = value; } }

    public TextLengthAttribute(int num) { this.length = num; }
}

public class MyClass
{
    [TextLength(10)]
    public string Property1;
    [TextLength(20)]
    public string Property2;
}

public class ClassReader
{
     public static void Main()
     {
          MyClass example = MyClass.GetTestData();

          PropertyInfo[] props = typeof(MyClass).GetProperties();
          foreach (PropertyInfo prop in props)
          {
               if (prop.ValueType == typeof(String) 
               {
                    TextLengthAttribute[] atts = 
                      (TextLengthAttribute)[]prop.GetCustomAttributes(
                           typeof(TextLengthAttribute), false);
                    if (prop.GetValue(example, null).ToString().Length > 
                         atts[0].Length) 
                        throw new Exception(prop.name + " was too long");
               }
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

注意:未经测试