Using RangeValidator with byte

纵然是瞬间 提交于 2019-12-11 17:23:01

问题


This is the property declaration in question:

 [RangeValidator(1,RangeBoundaryType.Inclusive,255,RangeBoundaryType.Inclusive,MessageTemplate = "StartFlexibility is out of range")]
    public byte StartFlexibility { get; set; }

When the validate method is called, a FormatException is thrown telling me that the value type needs to be Int32.

How to fix, please?


回答1:


well... the quick obvious fix will be change the type to short or int,

but another observation i want to do, is with the range. You are telling the RangeValidator to take a inclusive range between 1 and 256, but you just can assign a byte value till 255, maybe that's the compiler reason to cry out.

The RangeValidator is also infering the type of the Range from the parameters, so, try casting

[RangeValidator((byte) 1, ...



回答2:


As Jhonny says, cast to byte... but more like this

[RangeValidator(typeof(Byte), "1", RangeBoundaryType.Inclusive, "255", RangeBoundaryType.Inclusive, MessageTemplate = "Some message")]

The other option would be to call the range validator in a SelfValidation message and cast there.




回答3:


I've never used the RangeValidator class/attribute, but is it an issue that you have 256 as an upper bound when a byte can only get to 255?



来源:https://stackoverflow.com/questions/727017/using-rangevalidator-with-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!