【问题标题】:How to apply at once StringLength attribute to all properties within the class?如何立即将 StringLength 属性应用于类中的所有属性?
【发布时间】:2022-12-28 19:12:52
【问题描述】:

我有一个具有 ~400 个字符串属性的类(它是自动生成的)我想将 [StringLength(50)] 应用于类中的所有属性。如果不将属性复制粘贴 400 次,这是否可能?

【问题讨论】:

    标签: .net-core data-annotations asp.net-core-7.0


    【解决方案1】:

    有一种方法可以使用反射来实现,但这种方法将在运行时应用属性,而不是在编译时应用。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-31
      • 2012-06-09
      • 1970-01-01
      • 2015-11-22
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多