时间:2019-03-09 标签:c#syntaxicsugaroverloading
我有以下方法:
virtual public int nonNeg(int? numIn)
{
if ((numIn < 0) || (numIn ==null))
{
return 0;
}
else return (int)numIn;
}
我希望能够有一个可以接受字节、短整型或整数的方法,以将这些值强制为非负数。我怎样才能做到这一点?
I have the following method:
virtual public int nonNeg(int? numIn)
{
if ((numIn < 0) || (numIn ==null))
{
return 0;
}
else return (int)numIn;
}
I want to be able to have a single method which could take in either bytes, shorts, or ints to force these values to a nonnegative number. How could I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能是这样的(已测试):
Possibly something like this (tested):
我认为你可以这样做:
结果将是 22
或
结果将是 22.2
I think you can do this with:
result will be 22
OR
result will be 22.2
我通常不会建议这样做,但我突然想到以下重载应该涵盖您的大多数情况。它们将涵盖可空类型和不可空类型,编译器将选择适当的重载。
I would not normally suggest this, but off the top of my head the following overloads should cover most your cases. They will cover the nullable types and the non-nullable types, the compiler will select the appropriate overload.
或者只使用 Math.Max( 0, numIn)
Or just use
Math.Max( 0, numIn)