C# 扩展类与分布类

一、扩展类

//定义扩展方法
 public static class ExtsionString
    {
        public static string GetTop10(this string value)
        {
            return value.Substring(0, 10);
        }
    }


//调用扩展方法
            this.CreateTime.GetTop10();

二、部分类

 

 /// <summary>
    /// 学生类
    /// </summary>
    public partial class StudentModel
    {
        [DisplayName("编号")]
        public int ID { get; set; }

        [DisplayName("学生姓名")]
        public string Name { get; set; }

        [DisplayName("班级")]
        public string Class { get; set; }

        [DataType(DataType.Text)]
        [DisplayName("性别1-男,0-女")]
        public int Sex { get; set; }

        public string CreateTime { get; set; }

        partial void OnCreate();
    }
  //要想扩展StudentModel原有属性的信息描述,需要借助如下代码
    [MetadataType(typeof(StudentModelMetadata))]
    public partial class StudentModel
    {
        private class StudentModelMetadata : StudentModel
        {
            [StringLength(100)]
            public string Class { get; set; }
        }

        [StringLength(20,MinimumLength=5,ErrorMessage="请输入正确的邮箱信息")]
        [Required]//必填字段
        [RegularExpression(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")]
        public string Email { get; set; }

        [Range(10,40,ErrorMessage="年龄必须在10到40之间")]
        public int Age { get; set; }

        

        partial void OnCreate()
        {
            this.CreateTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //调用扩展方法
            this.CreateTime.GetTop10();
        }
        
    }

    public static class ExtsionString
    {
        public static string GetTop10(this string value)
        {
            return value.Substring(0, 10);
        }
    }
posted @ 2019-12-22 16:37  秋飘  阅读(1480)  评论(0编辑  收藏  举报