如何“泛化”这个扩展方法?
我有以下当前适用于 int 的方法?变量。我想将其扩展到任何可为空的数字变量(例如十进制?,双精度?等...)
public static bool IsNullOrInvalid(this System.Nullable<int> source)
{
return (source == null || source == -1);
}
我怎样才能实现这一目标?
I have the following method that currently works on int? variables. I'd like to extend it to any numeric nullable variables (e.g. decimal?, double?, etc...)
public static bool IsNullOrInvalid(this System.Nullable<int> source)
{
return (source == null || source == -1);
}
How can I pull this off?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
棘手的一点是弄清楚每种情况下“无效”的含义。如果“任何被认为小于数据类型默认值的值”都可以,您可以尝试:
编辑:如注释中所述,没有“数字”约束 - 在每个值类型上调用此方法都是有效的与其本身具有可比性,例如
DateTime
。没有办法避免这种情况 - 添加更多约束可能会稍微减少集合,但不会完全减少。至于与 -1 进行比较,您需要能够计算出每种类型的值“-1”。没有通用的方法可以做到这一点。您可以手动构建一个“对于我感兴趣的每种类型为-1”的
Dictionary
,但这会非常难看。如果-1无效,那么-2真的有效吗?这对我来说似乎很奇怪。
The tricky bit is working out what "invalid" means in each case. If "any value which is deemed less than the default for the data type" is okay, you could try:
EDIT: As noted in comments, there's no "numeric" constraint - it will be valid to call this method on every value type which is comparable with itself, such as
DateTime
. There's no way of avoiding that - adding more constraints would probably reduce the set slightly, but not completely.As for comparing with exactly -1, you'd need to be able to work out the value "-1" for every type. There's no generic way of doing that. You could manually build a
Dictionary<Type, object>
of "-1 for each type I'm interested in" but it would be pretty ugly.If -1 is invalid, is -2 really valid? That seems odd to me.
我认为这是不可能的,因为为了使其通用,它必须在所有类型中通用,并且 invalid 特定于整数。如果您只是重载该方法(double、float 等),编译器应该在您键入时找出您想要的方法
I don't think this is possible because to make this generic, it has to be generic across all types and invalid is specific to the integer. If you just make overloads of that method (double, float, etc.), the compiler should figure out which one you want when you type
你不能,要使之成为可能,你需要
但 c# 中没有数字的
Numeric
基类。问题是
source == -1
,没有与-1
一起使用的通用类或接口。你可以打破
-1
但是然后你需要像这样调用
You can not, to make that possible you would need
but there is no
Numeric
base class for numbers in c#.The problem is
source == -1
, there is no common class or interface that works with-1
.you could break out the
-1
But then you need to call like this