在.Net Standard 1.2中使用MaxLength属性

问题描述 投票:0回答:2

我的主要项目固定在.Net Framework 4.5.1中,并引用.Net Standard中的一个项目。出于兼容性原因,我无法将.Net Standard升级到1.2以上。.Net Standard项目需要从[MaxLength()]中声明具有System.ComponentModel.DataAnnotations属性的模型,但是该属性仅在2.0版本中可用。

在标准1.2中是否有解决方法具有[MaxLength()]属性?

enter image description here

c# .net-standard .net-framework-version maxlength
2个回答
0
投票

也许是创建自己的[MaxLength],是从ValidationAttribute继承?

您可以看一下,或者只是复制粘贴the current implementation


0
投票

您可以自己编写)

public class MyMaxLenght : ValidationAttribute
{
    private int _lenght;
    public MyMaxLenght(int lenght)
    {
        _lenght = lenght;
    }
    public override bool IsValid(object value)
    {
        if (value != null)
        {
            return value.ToString().Length > _lenght ? true : false;
        }
        return false;
    }
}

使用:

public class Test
{
    [MyMaxLenght(2)]
    public string Name;
}

或使用

[MaxLength()]

来自

使用System.ComponentModel.DataAnnotations;

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.