如何使用C#中的用戶注釋?
譯文【51CTO.com快譯】數(shù)據(jù)注釋(System.ComponentModel.DataAnnotations命名空間的一部分)是可以運用于類或類成員的屬性,以指定類之間的關(guān)系、描述數(shù)據(jù)如何在UI中顯示以及指定驗證規(guī)則。本文討論數(shù)據(jù)注釋、為什么數(shù)據(jù)注釋很有用以及如何在.NET Core應(yīng)用程序中使用它們。
若要使用本文提供的代碼示例,您應(yīng)該在系統(tǒng)中安裝Visual Studio 2019。如果還沒有安裝,可以在此處(https://visualstudio.microsoft.com/downloads/)下載Visual Studio 2019。
在Visual Studio 2019中創(chuàng)建控制臺應(yīng)用程序項目
首先,不妨在Visual Studio中創(chuàng)建一個.NET Core控制臺應(yīng)用程序項目。假設(shè)系統(tǒng)中已安裝Visual Studio 2019,按照下面概述的步驟在Visual Studio中創(chuàng)建新的.NET Core控制臺應(yīng)用程序項目。
- 啟動Visual Studio IDE。
- 點擊“創(chuàng)建新項目”。
- 在“創(chuàng)建新項目”窗口中,從顯示的模板列表中選擇“控制臺應(yīng)用程序(.NET Core)”。
- 點擊下一步。
- 在接下來顯示的“配置新項目”窗口中,指定新項目的名稱和位置。
- 點擊創(chuàng)建。
這將在Visual Studio 2019中創(chuàng)建一個新的.NET Core控制臺應(yīng)用程序項目。我們在本文后面將使用該項目來處理數(shù)據(jù)注釋。
添加System.ComponentModel.DataAnnotations命名空間
想使用本文給出的代碼示例,應(yīng)該將System.ComponentModel.DataAnnotations命名空間添加到您的程序。
注意,屬性用于指定類或?qū)傩缘脑獢?shù)據(jù)。數(shù)據(jù)注釋屬性大致分為以下幾類:
- 驗證屬性——用于對實體的屬性實施驗證規(guī)則。
- 顯示屬性——用于指定數(shù)據(jù)在用戶界面中應(yīng)如何顯示。
- 建模屬性——用于指定類之間存在的關(guān)系。
C#中的數(shù)據(jù)注釋屬性類
System.ComponentModel.Annotations命名空間包含幾個屬性類,它們可用于為您的實體類或數(shù)據(jù)控件定義元數(shù)據(jù)。最常用的屬性包括如下:
- 并發(fā)檢查
- 鍵
- 最大長度
- 必需
- 字符串長度
- 時間戳
C#中的數(shù)據(jù)注釋示例
在前面創(chuàng)建的控制臺應(yīng)用程序中的Author.cs文件中創(chuàng)建以下類。
- public class Author
- {
- [Required(ErrorMessage = "{0} is required")]
- [StringLength(50, MinimumLength = 3,
- ErrorMessage = "First Name should be minimum 3 characters and a maximum of 50 characters")]
- [DataType(DataType.Text)]
- public string FirstName { get; set; }
- [Required(ErrorMessage = "{0} is required")]
- [StringLength(50, MinimumLength = 3,
- ErrorMessage = "Last Name should be minimum 3 characters and a maximum of 50 characters")]
- [DataType(DataType.Text)]
- public string LastName { get; set; }
- [DataType(DataType.PhoneNumber)]
- [Phone]
- public string PhoneNumber { get; set; }
- [DataType(DataType.EmailAddress)]
- [EmailAddress]
- public string Email { get; set; }
- }
下列代碼片段表明了您如何創(chuàng)建Author類的實例并為其屬性賦予值。
- Author author = new Author();
- author.FirstName = "Joydip";
- author.LastName = "";
- author.PhoneNumber = "1234567890";
- author.Email = "joydipkanjilal@yahoo.com";
您可以在Program.cs文件的Main方法中編寫下列代碼片段,以驗證模型。
- ValidationContext context = new ValidationContext(author, null, null);
- List validationResults = new List();
- bool valid = Validator.TryValidateObject(author, context, validationResults, true);
- if (!valid)
- {
- foreach (ValidationResult validationResult in validationResults)
- {
- Console.WriteLine("{0}", validationResult.ErrorMessage);
- }
- }
ValidationContext這個類為您提供了進行驗證所在的上下文。如果驗證成功,Validator類的TryValidateObject靜態(tài)方法返回true,否則返回false。它還返回ValidationResults列表,詳細列出該模型未通過的所有驗證。最后,我們使用foreach循環(huán)來迭代處理ValidationResults列表,在控制臺窗口顯示錯誤消息。
完整的代碼片段如下所示,供您參考。
- public class Author
- {
- [Required(ErrorMessage = "{0} is required")]
- [StringLength(50, MinimumLength = 3,
- ErrorMessage = "First Name should be minimum 3 characters and a maximum of 50 characters")]
- [DataType(DataType.Text)]
- public string FirstName { get; set; }
- [Required(ErrorMessage = "{0} is required")]
- [StringLength(50, MinimumLength = 3,
- ErrorMessage = "Last Name should be minimum 3 characters and a maximum of 50 characters")]
- [DataType(DataType.Text)]
- public string LastName { get; set; }
- [DataType(DataType.PhoneNumber)]
- [Phone]
- public string PhoneNumber { get; set; }
- [DataType(DataType.EmailAddress)]
- [EmailAddress]
- public string Email { get; set; }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Author author = new Author();
- author.FirstName = "Joydip";
- author.LastName = ""; //No value entered
- author.PhoneNumber = "1234567890";
- author.Email = "joydipkanjilal@yahoo.com";
- ValidationContext context = new ValidationContext
- (author, null, null);
- List validationResults = new
- List();
- bool valid = Validator.TryValidateObject
- (author, context, validationResults, true);
- if (!valid)
- {
- foreach (ValidationResult validationResult in
- validationResults)
- {
- Console.WriteLine("{0}",
- validationResult.ErrorMessage);
- }
- }
- Console.ReadKey();
- }
- }
執(zhí)行程序后,應(yīng)該會看到控制臺窗口顯示的下列錯誤消息:
- LastName is required
在C#中創(chuàng)建自定義驗證屬性
想創(chuàng)建自定義驗證屬性類,您應(yīng)該擴展ValidationAttribute基礎(chǔ)類,并覆蓋IsValid方法,如下列代碼片段所示。
- [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
- public class IsEmptyAttribute : ValidationAttribute
- {
- public override bool IsValid(object value)
- {
- var inputValue = value as string;
- return !string.IsNullOrEmpty(inputValue);
- }
- }
下列代碼片段表明了你如何可以使用自定義屬性來裝飾Author類的FirstName和LastName屬性。
- [IsEmpty(ErrorMessage = "Should not be null or empty.")]
- public string FirstName { get; set; }
- [IsEmpty(ErrorMessage = "Should not be null or empty.")]
- public string LastName { get; set; }
數(shù)據(jù)注釋最初作為System. ComponentModel. DataAnnotations命名空間的一部分而引入到.NET 3.5中。此后,它已成為.NET中一種廣泛使用的功能。你可以充分利用數(shù)據(jù)注釋在單單一處定義數(shù)據(jù)驗證規(guī)則,因而沒必要一再重寫同樣的驗證代碼。
原文標題:How to use data annotations in C#,作者:Joydip Kanjilal
【51CTO譯稿,合作站點轉(zhuǎn)載請注明原文譯者和出處為51CTO.com】