C#中的以下代码将引发InvalidOperationException,因为未设置时不允许访问Value。
int? a = null;
Console.Writeline(a.Value);
我在AspNet.Core中具有以下代码:
public class Request
{
[Range(10, 20]
public int? Field1 {get; set;}
[Range(10, 20]
public MyStruct Field2 {get; set;}
}
public struct MyStruct
{
public int Value => throw new Exception();
}
[当模型验证发生时,框架会引发异常,因为它试图读取MyStruct
的所有属性,并且显然无法读取Value
。但是,如果我只有空字段,即使Value
也抛出异常,验证也可以正常工作。
是否有一些仅被硬编码为不可为空的魔术,或者有某种方式可以使我的代码具有相同的行为?即我希望验证不为我的课程抛出异常。
[我怀疑这是硬编码的检查,还是某种语法糖,使得Nullable
结构可以赋值并与null进行比较。
如果您查看RangeAttribute的reference source,您会在IsValid
方法的开头看到它:
// Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty.
if (value == null) {
return true;
}
所以这是设计使然。就像注释所建议的那样,如果您具有可为null的类型并想要确认是否有值,则应使用RequiredAttribute。
public class Request
{
[Required]
[Range(10, 20]
public int? Field1 {get; set;}
[Range(10, 20]
public MyStruct Field2 {get; set;}
}