如何创建自己的DataType?

Vis*_*hal 1 c#

我想创建自己的DataType名字positiveInteger.

我知道你在想什么?

你在想我应该uint在这里使用.但uint包含0,我只想要正数.

现在你可以告诉我创建一个叫做的类positiveInteger.是的,我可以创建一个Class被调用positiveInteger但我不知道如何实现该类,以便这个新的DataType只接受正整数值?

Dav*_*vid 5

如果你希望能够"接受"的价值观,这是(大多)编译为常int值,那么你就需要实现一个implicit转换positiveIntegerint

public class positiveInteger
{
    public static implicit operator positiveInteger(int source)
    {
        if(source <= 0) throw new ArgumentOutOfRangeException();
    }
}
Run Code Online (Sandbox Code Playgroud)

这将允许您像这样分配positiveInteger

positiveInteger number = 5;
Run Code Online (Sandbox Code Playgroud)

但是,它也可以分配一个int

int i = 5;
positiveInteger number = i;    // This will throw an exception when i <= 0
Run Code Online (Sandbox Code Playgroud)