解决方法
假设你有一系列的属性,你将通过反思来走过.任何字符串可能需要验证,以检查它们不超过一定量.
然后,您可以创建一个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"); } } } }
注意:未经测试