C# add to class in another DLL
...is it possible?
For example, can I add this simple function...
public static double Deg2Rad(double degrees) {
return Math.PI 开发者_高级运维/ 180 * degrees;
}
...to the Convert
class?
So (using the default..."usings") you can call
double radians = Convert.Deg2Rad(123);
Can this be done? If so, how?
No you can't, but you can add an Extension method to double
and call it like
double x = 180.0;
double y = Math.Cos( x.Deg2Rad() );
double z = Math.Sin( 0.5.Pi() );
in an static class add the following extension method:
public static class ExtensionMethods
{
public static double Deg2Rad(this double angle)
{
return Math.PI*angle/180.0;
}
public static double Pi(this double x)
{
return Math.PI*x;
}
}
No, it's not possible. You could use extensions if Convert
weren't static
, but no.
You could add an extension to double
though, using the this
keyword:
public static double Deg2Rad(this double degrees) {
return Math.PI / 180 * degrees;
}
And use it like so:
double radians = (123D).Deg2Rad();
You'll have to put your method in a static
class for it to work, though.
You can sort of get what you want. C# has "Extension Methods". This allow you to add methods to another class, even if that class is in another assembly that you do not have the source code for. However, you cannot add static functions to another class. You can only add instance methods.
For more information, see MSDN Extensions Methods.
No you can't, but you don't really need to - you can just declare your own static class instead, for example:
public static class MyConvert
{
public static double Deg2Rad(double degrees)
{
return Math.PI / 180 * degrees;
}
}
Usage:
double radians = MyConvert.Deg2Rad(123);
(Obviously MyConvert
is a rubbish name, but you get the idea).
The only difference between the above and having the method on the system Convert
class is that if its on the Convert
class it looks like a built-in function, but you are going to struggle to convince me thats actually a good thing (I like to know when I'm calling framework code vs code maintained internally).
Apart from what has been said here, there is also another option which is Partial classes (this won't apply to Convert).
If the class is declared partial, then you can add menthods via another partial class, even if it's in another assembly (DLL).
But, again, the class has to be originally declared partial for that to work.
精彩评论