";非静态字段、方法或属性需要对象引用';RxCard.dataobjects.Pharmacy.Area
本文关键字:对象引用 dataobjects Area Pharmacy RxCard quot 静态 字段 方法 属性 | 更新日期: 2023-09-27 17:59:08
我有一个自定义验证属性,需要将一些属性传递给它。但是,在应用该属性时会出现问题。我在向后学习.net,所以我倾向于陷入"更简单"的问题。我已经尝试过将该房产设为静态,但这打乱了我的部分视图。我该如何处理
属性:
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 "";
}
}
}
}
属性是设计时。您不能传递仅在运行时已知的值,如Area
我想你可能真的打算传递一个字符串,比如这个
[MinimumPhoneDigits(10, "Area")]