c# – 在dotnet / .NET中实现自定义属性的最佳方式是什么?
发布时间:2020-12-15 17:41:42 所属栏目:百科 来源:网络整理
导读:我真的不了解属性.我读过各种书籍他们的帖子,但我只是不明白. 既然我不了解他们,我也不明白如何有效地使用它们. 1)你能给我一个很好的定义什么属性是它用于什么? 2)你可以给我一个很好的代码示例在C#如何制作和使用自定义属性? 解决方法 假设你有一系列的
我真的不了解属性.我读过各种书籍他们的帖子,但我只是不明白.
既然我不了解他们,我也不明白如何有效地使用它们. 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"); } } } } 注意:未经测试 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |