一、擴展類
//定義擴展方法 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); } }