我可以使用 StringLengthAttribute 以编程方式测试 属性 以检查它是否有效吗?
Can I programmatically test a property with a StringLengthAttribute to check if it is valid?
鉴于我有:
[StringLength(10)]
public string Bibble {get; set;}
我可以单独查看 Bibble 是否有效吗?
我考虑过:
PropertyInfo[] props = typeof(MyBibbleObject).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
StringLengthAttribute stringLengthAttribute = attr as StringLengthAttribute;
if (stringLengthAttribute != null)
{
string propName = prop.Name;
// Could be IsValid?
stringLengthAttribute.IsValid()
}
}
}
但是 IsValid 方法需要一个对象,这是我没有预料到的。我想知道是否有更好的方法来确定它是否有效。我必须在每个 属性 的基础上进行。
您可以为此使用内置 Validator
class。它的用法有点模糊,但仍然是:
// instance is your MyBibbleObject object
var ctx = new ValidationContext(instance);
// property to validate
ctx.MemberName = "Bibble";
// this will store results of validation. If empty - all fine
var results = new List<ValidationResult>();
// pass value to validate (it won't take it from your object)
Validator.TryValidateProperty(instance.Bibble, ctx, results);
鉴于我有:
[StringLength(10)]
public string Bibble {get; set;}
我可以单独查看 Bibble 是否有效吗?
我考虑过:
PropertyInfo[] props = typeof(MyBibbleObject).GetProperties();
foreach (PropertyInfo prop in props)
{
object[] attrs = prop.GetCustomAttributes(true);
foreach (object attr in attrs)
{
StringLengthAttribute stringLengthAttribute = attr as StringLengthAttribute;
if (stringLengthAttribute != null)
{
string propName = prop.Name;
// Could be IsValid?
stringLengthAttribute.IsValid()
}
}
}
但是 IsValid 方法需要一个对象,这是我没有预料到的。我想知道是否有更好的方法来确定它是否有效。我必须在每个 属性 的基础上进行。
您可以为此使用内置 Validator
class。它的用法有点模糊,但仍然是:
// instance is your MyBibbleObject object
var ctx = new ValidationContext(instance);
// property to validate
ctx.MemberName = "Bibble";
// this will store results of validation. If empty - all fine
var results = new List<ValidationResult>();
// pass value to validate (it won't take it from your object)
Validator.TryValidateProperty(instance.Bibble, ctx, results);