c# - C#验证嵌套类的自定义数据类型(枚举)的属性内的属性
问题描述
我需要以下帮助。我有一个基类,比如 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
}
解决方案
您不应该在属性设置器内部进行验证。你需要验证你的整个对象看看例子: 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;
}
}
推荐阅读
- android - 如何在我的 android 应用程序上为我的 Firestore 中的每个集合动态创建布局元素?
- java - 如何使用 Stream Parallel Java 执行矩阵计算?
- facebook - 有没有办法删除 facebook 像素事件?
- android - getIntent().getExtras() 上的空指针;
- ios - SwiftUi 多个 foreach
- python-3.x - 如何修复:从守护进程收到的截断或过大的响应标头
- haskell - 如何从字符串中读取/解析 Int
- excel - 试图识别从一个数据库分割到另一个数据库的字符串(使用 Excel),最好使用什么公式/其他方法?
- haskell - Haskell:比较字符
- javascript - Node.js xml2js - 创建站点地图属性时被忽略