为什么IsNan是Double类而不是实例属性的静态方法? [英] Why IsNan is a static method on the Double class instead of an instance property?

查看:784
本文介绍了为什么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#具有扩展属性,那将会更好(语法)以上是关于你最近可以得到的,但它应该内联相当不错。






< S>更新;考虑它,静态和实例之间有另一个区别;始终使用 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类而不是实例属性的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆