我想创建我自己的 DataType
,名为 positiveInteger
。
我知道你在想什么?
你认为我应该在这里使用 uint
。
但是 uint
包含 0
,我只想要正数。
现在你可以告诉我创建一个名为 positiveInteger
的类。
是的,我可以创建一个名为 positiveInteger
的 Class
,但我不知道如何实现该类以使这个新的 DataType 只接受正整数值?
最佳答案
如果您希望能够“接受”值(mostly)编译为常量int
值,那么您需要实现一个implicit
。从 int
positiveInteger
public class positiveInteger
{
public static implicit operator positiveInteger(int source)
{
if(source <= 0) throw new ArgumentOutOfRangeException();
}
}
这将允许您像这样分配一个 positiveInteger
positiveInteger number = 5;
但是,它也可以分配一个 int
值
int i = 5;
positiveInteger number = i; // This will throw an exception when i <= 0
关于c# - 如何创建自己的数据类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26433276/