認(rèn)識(shí)Fluent Vaidation.
看到NopCommerce項(xiàng)目中用到這個(gè)組建是如此的簡(jiǎn)單,將數(shù)據(jù)驗(yàn)證從業(yè)務(wù)實(shí)體類中分離出來(lái),真是一個(gè)天才的想法,后來(lái)才知道這個(gè)東西是一個(gè)開(kāi)源的輕量級(jí)驗(yàn)證組建。
Fluent Validation 翻譯為:流暢驗(yàn)證
開(kāi)源Codeplex其主頁(yè)簡(jiǎn)介:該組件是一個(gè)輕量級(jí)的.NET類庫(kù),使用流暢的接口定義和lambda表達(dá)式為構(gòu)建一個(gè)業(yè)務(wù)類的驗(yàn)證規(guī)則(A small validation library for .NET that uses a fluent interface and lambda expression for building validation rules for you business objects.)
這個(gè)類庫(kù)不僅僅可以使用的asp.net mvc項(xiàng)目中,普通的類庫(kù)中也可以使用,當(dāng)然在asp.net form項(xiàng)目中也支持。
怎么使用:
是不是好用,還要看使用時(shí)是否真的像其官網(wǎng)建議描述一樣。我比較喜歡其官網(wǎng)上的例子,一眼就能看出用法上的感覺(jué),絕對(duì)是如其名,流暢,這個(gè)也一種解釋型語(yǔ)言常見(jiàn)的的一種用法,無(wú)限的對(duì)一個(gè)類型支持無(wú)限度個(gè)屬性擴(kuò)展。
業(yè)務(wù)實(shí)體類:
代碼如下:
public class Person
{
public string NameField;
public int Id { get; set; }
public string Surname { get; set; }
public string Forename { get; set; }
public List<Person> Children { get; set; }
public string[] NickNames { get; set; }
public DateTime DateOfBirth { get; set; }
public int? NullableInt { get; set; }
public Person()
{
Children = new List<Person>();
Orders = new List<Order>();
}
public int CalculateSalary()
{
return 20;
}
public Address Address { get; set; }
public IList<Order> Orders { get; set; }
public string Email { get; set; }
public decimal Discount { get; set; }
public double Age { get; set; }
public int AnotherInt { get; set; }
public string CreditCard { get; set; }
public int? OtherNullableInt { get; set; }
}
public interface IAddress
{
string Line1 { get; set; }
string Line2 { get; set; }
string Town { get; set; }
新聞熱點(diǎn)
疑難解答
圖片精選