C# 验证嵌套 class 的自定义数据类型(枚举)的 属性 内的属性
C# Validate attribute inside property of custom data type (enum) of a nested class
我需要以下方面的帮助。我有一个基础 class,比如 MyClass,它有一个嵌套的 class,比如 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
}
您不应在 属性 setter 内进行验证。您需要验证整个对象
看看例子:
https://www.geekinsta.com/manually-validate-with-data-annotations/
this._Name = system_name;
this.Standard = new Standard_One();
var ctx = new ValidationContext(this.Standard);
// A list to hold the validation result.
var results = new List < ValidationResult > ();
if (!Validator.TryValidateObject(this.Standard, ctx, results, true)) {
foreach(var errors in results) {
Console.WriteLine("Error {0}", errors);
return;
}
}
我需要以下方面的帮助。我有一个基础 class,比如 MyClass,它有一个嵌套的 class,比如 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
}
您不应在 属性 setter 内进行验证。您需要验证整个对象 看看例子: https://www.geekinsta.com/manually-validate-with-data-annotations/
this._Name = system_name;
this.Standard = new Standard_One();
var ctx = new ValidationContext(this.Standard);
// A list to hold the validation result.
var results = new List < ValidationResult > ();
if (!Validator.TryValidateObject(this.Standard, ctx, results, true)) {
foreach(var errors in results) {
Console.WriteLine("Error {0}", errors);
return;
}
}