简体   繁体   中英

How to apply at once StringLength attribute to all properties within the class?

I have a class with ~400 string properties(it's auto-generated) I would like to apply [StringLength(50)] to all properties within the class. Is that is possible without copy-pasting the attribute 400 times?

There is a way to do it using reflection, but this approach will apply the attributes at runtime, not at compile time.

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);
    }
}

Then you can call AddStringLengthAttribute(typeof(YourClass), 50);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM