【发布时间】:2022-12-28 19:12:52
【问题描述】:
我有一个具有 ~400 个字符串属性的类(它是自动生成的)我想将 [StringLength(50)] 应用于类中的所有属性。如果不将属性复制粘贴 400 次,这是否可能?
【问题讨论】:
标签: .net-core data-annotations asp.net-core-7.0
我有一个具有 ~400 个字符串属性的类(它是自动生成的)我想将 [StringLength(50)] 应用于类中的所有属性。如果不将属性复制粘贴 400 次,这是否可能?
【问题讨论】:
标签: .net-core data-annotations asp.net-core-7.0
有一种方法可以使用反射来实现,但这种方法将在运行时应用属性,而不是在编译时应用。
public static void AddStringLengthAttribute(Type type, int maxLength)
{
var properties = type.GetProperties();
foreach (var property in properties)
{
var attribute = new StringLengthAttribute(maxLength);
property.SetCustomAttribute(attribute);
}
}
然后你可以拨打AddStringLengthAttribute(typeof(YourClass), 50);
【讨论】: