[英]Custom Validation Attribute
目前我嘗試通過同一類的另一個屬性來驗證一個屬性。 我收到一個錯誤,告訴我以下內容:
非靜態字段、方法或屬性需要對象引用
對於以下代碼片段,這種錯誤對我來說絕對有意義。 但無論如何,由於屬性 B 的值(在我的示例 Level 中),我嘗試驗證屬性 A(在我的示例 OrderNumber 中)。
是否有可能通過使用驗證注釋來做到這一點?
這是目前我的代碼:
public class A
{
/// <summary>
/// Level
/// </summary>
public string Level { get; set; }
public B B {get;set;}
}
public class B
{
/// <summary>
/// Order Number
/// </summary>
[Level(A.Level)]
public int? OrderNumber { get; set; }
}
public class LevelAttribute : ValidationAttribute
{
private string Dlevel { get; set; }
public LevelAttribute(string dlevel)
{
this.Dlevel = dlevel;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value!=null && (Dlevel.Equals("D1")||Dlevel.Equals("D2")))
{
return new ValidationResult("Invalid Error Message");
}
return ValidationResult.Success;
}
}
感謝幫助。
在自定義屬性構造函數中無法直接引用實例成員(方法、屬性、字段)。 但是有一種間接的方式,通過定義屬性名,通過反射解析對應的屬性值:
public class A
{
public A()
{
Level = "D3";
}
public string Level { get; set; }
public B B { get; set; }
}
public class B
{
[Level("MyNamespace.A.Level")]
public int? OrderNumber { get; set; }
}
public class LevelAttribute : ValidationAttribute
{
private string PropName { get; set; }
public LevelAttribute(string prop)
{
this.PropName = prop;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
System.Reflection.PropertyInfo property = null;
object objectinstance = null;
if (this.PropName.Contains("."))
{
string classname = PropName.Substring(0, PropName.LastIndexOf("."));
string prop = PropName.Substring(PropName.LastIndexOf(".") + 1);
Type type = Type.GetType(classname);
objectinstance = System.Activator.CreateInstance(type);
property = type.GetProperty(prop, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
}
else
{
objectinstance = validationContext.ObjectInstance;
property = validationContext.ObjectInstance.GetType().GetProperty(this.PropName, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
}
object propertyvalue = property.GetValue(objectinstance, new object[0]);
if (value != null && propertyvalue != null && (propertyvalue.Equals("D1") || propertyvalue.Equals("D2")))
{
return new ValidationResult("Invalid Error Message");
}
return ValidationResult.Success;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.