C# 静态扩展方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/866921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:48:01  来源:igfitidea点击:

Static extension methods

c#extension-methods

提问by Midhat

Possible Duplicate:
Can I add extension methods to an existing static class?

可能的重复:
我可以向现有的静态类添加扩展方法吗?

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

有什么方法可以向类添加静态扩展方法。

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

特别是我想重载 Boolean.Parse 以允许 int 参数。

采纳答案by BFree

In short, no, you can't.

简而言之,不,你不能。

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

长答案,扩展方法只是语法糖。IE:

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

如果你有一个关于字符串的扩展方法,让我们说:

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

When you then call it:

当你调用它时:

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.

如您所见,静态方法无法做到这一点。

And another thing just dawned on me: what would really be the pointof 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 benefit in being able to do:

而就明白了我另一件事:什么,这真是一点是能够在现有的类添加静态方法?您可以拥有自己的辅助类来做同样的事情,那么能够这样做的真正好处是什么:

Bool.Parse(..)

vs.

对比

Helper.ParseBool(..);

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

并没有真正带来太多...

回答by Ray

It doesn't look like you can. See here for a discussion on it

看起来你做不到。有关它的讨论,请参见此处

I would very much like to be proven wrong though.

我非常希望被证明是错误的。

回答by BobbyShaftoe

No, but you could have something like:

不,但你可以有类似的东西:

bool b;
b = b.YourExtensionMethod();

回答by bsneeze

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

特别是我想重载 Boolean.Parse 以允许 int 参数。

Would an extension for int work?

int 的扩展会起作用吗?

public static bool ToBoolean(this int source){
    //do it
    //return it
}

Then you can call it like this:

然后你可以这样称呼它:

int x = 1;

bool y=x.ToBoolean();