[英]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.