【发布时间】:2021-08-25 13:19:23
【问题描述】:
我需要以下方面的帮助。我有一个基类,比如 MyClass,它有一个嵌套类,比如 StandardOne。在 StandardOne 中,我有一些我希望用属性验证的属性。 这些属性适用于常见数据类型,即字符串、字符等,但我有一些基于简单枚举的属性。那时,属性的验证不起作用,根据错误提示,因为强制转换。我什么都试过了,可惜没有成功。
- 谁能帮我解决这个错误?
- 我看到我在验证属性时一次又一次地使用相同类型的代码;关于如何(也许?)将其转换为扩展的任何建议?我不知道。欢迎任何建议。
例子:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
public class Program
{
public static void Main()
{
Console.WriteLine("Start");
}
public class MyClass
{
public Standard_One Standard {get;set;}
private string _Name;
public MyClass(string system_name)
{
this._Name = system_name;
this.Standard = new Standard_One();
}
public class Standard_One
{
private string _MyProperty1;
[Required(AllowEmptyStrings = false, ErrorMessage = "Field is mandatory.")]
[StringLength(32, ErrorMessage = "Field value should be between Minimum 1 and Maximum 32 characters.", MinimumLength = 1)]
[RegularExpression(@"^[a-zA-Z0-9.-]$", ErrorMessage = "Non-valid characters included.")]
public string MyProperty1
{
get
{ return _MyProperty1; }
set
{
var context = new ValidationContext(value, null, null);
var results = new List<ValidationResult>();
var attributes = typeof(Standard_One)
.GetProperty("MyProperty1")
.GetCustomAttributes(true)
.OfType<ValidationAttribute>()
.ToArray();
// All ok
if (!Validator.TryValidateValue(value, context, results, attributes))
{
foreach (var result in results)
{Console.WriteLine("MyProperty1 error: {0}", result.ErrorMessage); }
}
else
{
Console.WriteLine("MyProperty1 set to {0}.", value);
_MyProperty1 = value;
}
}
}
public enum field_sys_type { A, B, G }
[Required(AllowEmptyStrings = false, ErrorMessage = "Field is mandatory.")]
[StringLength(32, ErrorMessage = "Field value should be between Minimum 1 and Maximum 32 characters.", MinimumLength = 1)]
[RegularExpression(@"^[a-zA-Z0-9.-]$", ErrorMessage = "Non-valid characters included.")]
public field_sys_type MyProperty2
{
get
{ return _MyProperty2; }
set
{
var context = new ValidationContext(value, null, null);
var results = new List<ValidationResult>();
var attributes = typeof(Standard_One)
.GetProperty("MyProperty2")
.GetCustomAttributes(true)
.OfType<ValidationAttribute>()
.ToArray();
// THROWS System.InvalidCastException: 'Unable to cast object of type 'field_sys_type' to type 'System.String'.'
if (!Validator.TryValidateValue(value, context, results, attributes))
{
foreach (var result in results)
{Console.WriteLine("MyProperty2 error: {0}", result.ErrorMessage); }
}
else
{
Console.WriteLine("MyProperty2 set to {0}.", value);
_MyProperty2 = value;
}
}
}
}
} // end of MyClass
}
【问题讨论】:
-
在枚举属性上使用“StringLength”或“RegularExpression”验证器是什么意思?它不是字符串属性,所以它没有长度,当然也不会匹配任何正则表达式。
-
@Quercus 你绝对是对的,复制/粘贴有关属性的代码(我有很多,但肯定不是枚举声明的属性)。你是绝对正确的。抱歉这个有点混乱的例子..
标签: c# validation properties attributes inner-classes