微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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");
               }
          }
     }
}

注意:未经测试

原文地址:https://www.jb51.cc/csharp/96590.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐