这不正是你的设计,但我已经使用属性来执行一些我的课的性质有一个理想值。我耗费了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之前,我将检查每个属性是否符合它们的属性标记。