這不正是你的設計,但我已經使用屬性來執行一些我的課的性質有一個理想值。我耗費了web服務,我要發一些信息,一些字段的要求進行價值,別人不...
[Serializable]
[AttributeUsage(AttributeTargets.Property)]
public class RequiredAttribute : Attribute
{
private CheckType[] _requiredtype;
public RequiredAttribute(params CheckType[] type)
{
_requiredtype = type;
}
public CheckType[] Requires
{
get { return _requiredtype; }
}
public static bool CheckRequirements(object applyto, out string errormessages)
{ ... }
private static bool RequiredSucceeded(object applyto, StringBuilder resultmessage)
{ ... }
}
[Serializable]
public enum CheckType
{
HasValue, // Checks that the property value is not null
CheckMinRequirements, // Will enforce the validation of properties on defined types
IsNotNullorEmpty, // For strings
HasElements, // Elements exist on arrays
ElementsRequirements // for collections
}
現在有使用屬性
[Serializable]
public class PurchaseInsurance
{
[Required(CheckType.IsNotNullorEmpty)]
public string PartnerBookingID
{
get;
set;
}
[Required(CheckType.IsNotNullorEmpty)]
public string Currency
{
get;
set;
}
public string ReferringURL;
[Required(CheckType.HasValue, CheckType.CheckMinRequirements)]
public PurchaserInfo Purchaser
{
get;
set;
}
[Required(CheckType.HasValue, CheckType.ElementsRequirements)]
public InsuranceProduct[] Products
{
get;
set;
}
...
}
一個類的實例
在將數據發送到webService之前,我將檢查每個屬性是否符合它們的屬性標記。