C# - 检测字符串何时超出 [MaxLength(#)] 并截断?

Jer*_*rst 1 c# truncate maxlength

我有一个像这样的对象类:

public class MyObject
{
   [MaxLength(128)]
   public string Name {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

但是,当我使用超过 128 个字符的名称字符串创建 MyObject 时,我可以设置它并且它可以工作。这会导致问题,因为当我将此对象插入数据库时​​,由于字符串对于表中的该列太长,因此会出现异常。

我将如何确保太长的字符串被截断?我怎样才能检测到这种情况何时发生,以便我可以记录它?

Nic*_*ler 5

在设置器中您可以添加一些验证。

public class MyObject
{
    private string name;
    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (string.IsNullOrEmpty(value) || value.Length <= 128)
            {
                name = value;
            }
            else
            {
                //log? do something or truncate
                name = value.Substring(0, 127);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,我不喜欢它,但我尝试让它与属性一起使用,并使其更容易使用辅助类进行扩展。

public class MyObject
{
    private string name;
    [MaxLength(128, ErrorMessage = "String is longer than {1} characters and has been truncated.")]
    public string Name
    {
        get { return name; }
        set
        {
            name = value.Validate(GetType().GetProperty(MethodBase.GetCurrentMethod().Name.Substring(4)).GetCustomAttributes(false));
        }
    }
}

public static class Tools
{
    public static string Validate(this string value, object[] attributes)
    {
        if (attributes.FirstOrDefault(x => x is MaxLengthAttribute) is MaxLengthAttribute maxLengthAttribute)
        {
            if (maxLengthAttribute.IsValid(value))
            {
                return value;
            }
            else
            {
                //LogMethod(maxLengthAttribute.FormatErrorMessage(maxLengthAttribute.MaximumLength.ToString()));
                return value.Substring(0, maxLengthAttribute.Length - 1);
            }
        }
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)