how to set compile time validation on class instance members

前端 未结 2 1075
Happy的楠姐
Happy的楠姐 2021-01-21 12:32

I have created a class like below:

class myclass
{
  Public  int myint;
}

Now I want to restrict the range of myint(min 5 and max 10).

相关标签:
2条回答
  • 2021-01-21 12:42

    You don't have that out-of-the-box in .NET, but there're some validation engines that let you validate an instance of some object against some rules.

    Read about:

    • NHValidator: It can be used standalone, read this article: http://ayende.com/Blog/archive/2009/05/01/nhibernate-validator.aspx

    • Microsoft Application Validation Block: http://msdn.microsoft.com/en-us/library/ff650484.aspx

    I'll suggest you to use NHValidator, because it's very easy-to-use, needs zero configuration and it has a good community support. Another good point is you can use in any layer (business, presentation...) because it's attribute-oriented, meaning that you don't need to inherit any class or implement an interface in order to use it anywhere!

    0 讨论(0)
  • 2021-01-21 13:00

    It's experimental, but you could look into Spec#. It can provide you with more compile-time checks. Code Contracts are another option (but that's only available in certain editions of Visual Studio).

    Edit:

    Looks like code contacts may now be available as a standalone download! See this page!

    0 讨论(0)
提交回复
热议问题