我有一个自定义验证属性,我需要传递一些属性。但是,应用该属性本身时出现了我的问题。我正在向后学习,所以我倾向于陷入“更简单”的问题。我已经尝试过让这个属性变成静态的,但是这使我的观点变得混乱。我该如何解决这个问题?
属性:“对象引用是必需的非静态字段,方法或属性'RxCard.dataobjects.Pharmacy.Area.Get'”
public class MinimumPhoneDigits : ValidationAttribute
{
public string[] _properties;
public int _expectedsize;
public MinimumPhoneDigits(int expectedsize, params string[] properties)
{
ErrorMessage = "Not the expected size!";
_properties = properties;
_expectedsize = expectedsize;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_properties == null || _properties.Length < 1)
{
return new ValidationResult("WOAH! Not the right size.");
}
int totalsize = 0;
foreach (var property in _properties)
{
var propinfo = validationContext.ObjectType.GetProperty(property);
if (propinfo == null)
return new ValidationResult(string.Format("could not find {property}"));
var propvalue = propinfo.GetValue(validationContext.ObjectInstance, null) as string;
if (propvalue == null)
return new ValidationResult(string.Format("wrong property for {property}"));
totalsize += propvalue.Length;
}
if (totalsize != _expectedsize)
return new ValidationResult(ErrorMessage);
return ValidationResult.Success;
}
}
类:
public class Pharmacy
{
[MinimumPhoneDigits(10, Area)]
public string PhoneNumber
{
get
{
return _phoneNumber;
}
set
{
_phoneNumber = value;
}
}
private string _phoneNumber;
public string Area
{
get
{
try
{
return _phoneNumber.Split(new char[] { '(', ')', '-' }, StringSplitOptions.RemoveEmptyEntries)[0].Trim();
}
catch
{
return "";
}
}
}
}
哪里是你的自定义属性实际上定义的值? –
你需要告诉我们你在哪里获得'Pharmacy.Area',但是,一般来说,'catch {return“”; }'是问题集的成员,而不是解决方案集的成员。 –
你的代码吞噬抛出的任何异常,顺便说一句。 – Tim