【小5聊】C#基础之数据模型的简单实用

【Nuget安装】

选择适合自己的版本安装,System.ComponentModel.Annotations.dll

system.componentmodel.annotations\5.0.0\ref\netstandard2.0\System.ComponentModel.Annotations.dll

【简单使用】

1、字符串类型,默认可不设置值,不会报异常

        /// <summary>
        /// 字符串类型
        /// </summary>
        [Display(Name = "str")]
        public string str{ get; set; }

2、十进制数据类型,如果默认下面设置会报错,The value '' is invalid.


        /// <summary>
        /// 十进制数据类型
        /// </summary>
        [Display(Name = "deci")]
        public decimal deci { get; set; }

如果界面字段允许为空,那么就需要在数据类型后面加上个?问号,比如下面


        /// <summary>
        /// 十进制数据类型
        /// </summary>
        [Display(Name = "deci")]
        public decimal? deci { get; set; }

【自定义验证】

重载、重写、覆写,分别指的是overload、override、new

这里是对属性方法进行重写

using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace BaseSet.Application.BuildInfo.Dto
{
    public class CustomDataValidate : ValidationAttribute
    {

    }

    /// <summary>
    /// 验证经纬度
    /// </summary>
    public class ValidateLongLatAttribute : ValidationAttribute
    {
        /// <summary>
        /// 重写
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override bool IsValid(object value)
        {
            if (!(value is string))
            {
                if (value == null) return true;
                decimal temp = 0;
                decimal.TryParse(value.ToString(),out temp);
                if (temp <= 0) return true;
            }

            var val = value.ToString();
            return Regex.IsMatch(val, @"^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,15})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,15}|180)$");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lmy_520/article/details/112171169
今日推荐