静态扩展方法 [英] Static extension methods

查看:129
本文介绍了静态扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/249222/can-i-add-extension-methods-to-an-existing-static-class\">Can我想补充扩展方法,现有的静态类?

有什么办法,我可以添加静态扩展方法的类。

Is there any way I can add a static extension method to a class.

具体我想重载Boolean.Parse允许一个int参数。

specifically I want to overload Boolean.Parse to allow an int argument.

推荐答案

在短,不,你不能。

长一点的回答,扩展方法只是语法糖。 IE浏览器:

Long answer, extension methods is just syntactic sugar. IE:

如果你对字符串的扩展方法让我们说:

if you have an extension method on string let's say:

public static string SomeStringExtension(this string s)
{
   //whatever..
}

当你然后调用它:

myString.SomeStringExtension();

编译器只是把它变成:

the compiler just turns it into:

ExtensionClass.SomeStringExtension(myString);

因此​​,大家可以看到,有没有办法做到这一点的静态方法。

So as you can see, there's no way to do that for static methods.

和刚才我恍然大悟另一件事:什么会真正做到了的点能够对现有的类添加静态方法的?你可以有自己的助手类,它做同样的事情,所以什么是真正能够做到benfit:

And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benfit in being able to do:

Bool.Parse(..)

VS

Helper.ParseBool(..);

并没有真正带来多大的表...

Doesn't really bring much to the table...

这篇关于静态扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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