我真的不了解属性.我读过各种书籍他们的帖子,但我只是不明白.
既然我不了解他们,我也不明白如何有效地使用它们.
解决方法
假设你有一系列的属性,你将通过反思来走过.任何字符串可能需要验证,以检查它们不超过一定量.
然后,您可以创建一个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 举报,一经查实,本站将立刻删除。