为什么IsNan是Double类而不是实例属性的静态方法?

编程入门 行业动态 更新时间:2024-10-07 14:27:07
本文介绍了为什么IsNan是Double类而不是实例属性的静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问题在标题中,为什么:

return double.IsNaN(0.6d)&& double.IsNaN(X);

而不是

code> return(0.6d).IsNaN&& x.IsNaN;我要问,因为在实现具有与NaN相同含义的特殊值的自定义结构时,我倾向于另外,属性的性能通常更好,因为它避免复制堆栈上的结构体来调用IsNaN静态方法(而且由于我的属性是' t虚拟没有自动打包的风险)。确定这不是一个内置类型的问题,因为JIT可以优化这个简单。

我现在最好的猜测是,因为你不能同时拥有该属性和静态方法在双重类中具有相同的名称,它们赞成使用java启发的语法。 (实际上,你可以同时定义一个get_IsNaN属性getter,另一个定义一个IsNaN静态方法,但是在支持属性语法的任何.Net语言中都会混淆)

解决方案

有趣的问题;不知道答案 - 但是如果真的错了你,你可以声明一个扩展方法,但它仍然会使用堆栈等。

static bool IsNaN(this double value) { return double.IsNaN(value); } static void Main() { double x = 123.4; bool isNan = x.IsNaN(); }

如果C#具有扩展属性,那将会更好(语法)以上是关于你最近可以得到的,但它应该内联相当不错。

更新;考虑它,静态和实例之间有另一个区别;始终使用 callvirt 调用实例方法,而不是调用,即使其它类型的密封是不可空的。那么也许有一个性能优势让它静态吗?幸运的是,扩展方法仍然是静态的,所以你可以保留这种行为。

The question is in the title, why :

return double.IsNaN(0.6d) && double.IsNaN(x);

Instead of

return (0.6d).IsNaN && x.IsNaN;

I ask because when implementing custom structs that have a special value with the same meaning as NaN I tend to prefer the second.

Additionally the performance of the property is normally better as it avoid copying the struct on the stack to call the IsNaN static method (And as my property isn't virtual there is no risk of auto-boxing). Granted it isn't really an issue for built-in types as the JIT could optimize this easilly.

My best guess for now is that as you can't have both the property and the static method with the same name in the double class they favored the java-inspired syntax. (In fact you could have both as one define a get_IsNaN property getter and the other an IsNaN static method but it will be confusing in any .Net language supporting the property syntax)

解决方案

Interesting question; don't know the answer - but if it really bugs you, you could declare an extension method, but it would still use the stack etc.

static bool IsNaN(this double value) { return double.IsNaN(value); } static void Main() { double x = 123.4; bool isNan = x.IsNaN(); }

It would be nicer (for the syntax) if C# had extension properties, but the above is about the closest you can get at the moment, but it should "inline" quite well anyway.

Update; thinking about it, there is another difference between static and instance; C# always calls instance methods with "callvirt" rather than "call", even if ther type is sealed an non-nullable. So perhaps there is a performance benefit from having it static? Luckily, extension methods still count as static, so you get to retain this behavior.

更多推荐

为什么IsNan是Double类而不是实例属性的静态方法?

本文发布于:2023-11-29 15:42:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646830.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   而不是   实例   属性   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!