问题
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.
回答1:
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. 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 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 benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
回答2:
specifically I want to overload Boolean.Parse to allow an int argument.
Would an extension for int work?
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();
回答3:
It doesn't look like you can. See here for a discussion on it
I would very much like to be proven wrong though.
回答4:
You could add an extension method to int
public static class IntExtensions
{
public static bool Parse(this int value)
{
if (value == 0)
{
return true;
}
else
{
return false;
}
}
public static bool? Parse2(this int value)
{
if (value == 0)
{
return true;
}
if (value == 1)
{
return false;
}
return null;
}
}
used like this
bool bool1 = 0.Parse();
bool bool2 = 1.Parse();
bool? bool3 = 0.Parse2();
bool? bool4 = 1.Parse2();
bool? bool5 = 3.Parse2();
回答5:
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
来源:https://stackoverflow.com/questions/866921/static-extension-methods