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

我真的不了解属性.我读过各种书籍他们的帖子,但我只是不明白.

既然我不了解他们,我也不明白如何有效地使用它们.

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

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

解决方法

假设你有一系列的属性,你将通过反思来走过.任何字符串可能需要验证,以检查它们不超过一定量.

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

码:

public class TextLengthAttribute : Attribute
{
    private int length;
    public int Length { get { retrun 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");
               }
          }
     }
}

注意:未经测试

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...