我有一个类~400字符串属性(它是自动生成的),我想将[StringLength(50)]
应用到类中的所有属性。如果不复制粘贴属性400次,这是可能的吗?
有一种使用反射的方法,但是这种方法将在运行时应用这些属性,而不是在编译时应用。
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);