C# 添加到另一个 DLL 中的类
...是否可以?
例如,我可以将这个简单的函数...
public static double Deg2Rad(double degrees) {
return Math.PI / 180 * degrees;
}
...添加到 Convert
类中吗? 所以(使用默认的...“usings”)你可以调用
double radians = Convert.Deg2Rad(123);
这可以完成吗?如果是这样,怎么办?
...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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,您不能,但您可以向
double
添加扩展方法并像在静态类中一样调用它,添加以下扩展方法:
No you can't, but you can add an Extension method to
double
and call it likein an static class add the following extension method:
不,这是不可能的。如果
Convert
不是static
,您可以使用扩展,但不行。不过,您可以使用
this
关键字向double
添加扩展:并像这样使用它:
您必须将您的方法放入
static class 才能正常工作。
No, it's not possible. You could use extensions if
Convert
weren'tstatic
, but no.You could add an extension to
double
though, using thethis
keyword:And use it like so:
You'll have to put your method in a
static
class for it to work, though.你可以得到你想要的东西。 C# 有“扩展方法”。这允许您向另一个类添加方法,即使该类位于您没有源代码的另一个程序集中。但是,您不能将静态函数添加到另一个类中。您只能添加实例方法。
有关详细信息,请参阅 MSDN 扩展方法。
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.
不,你不能,但你真的不需要 - 你可以只声明你自己的静态类,例如:
用法:(
显然
MyConvert
是一个垃圾名称,但你明白了)。上述方法与系统
Convert
类上的方法之间的唯一区别是,如果它位于Convert
类上,它看起来像一个内置函数,但您要努力说服我这实际上是一件好事(我想知道何时调用框架代码与内部维护的代码)。No you can't, but you don't really need to - you can just declare your own static class instead, for example:
Usage:
(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 theConvert
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).除了这里所说的之外,还有另一个选项 部分类(这不适用于 Convert)。
如果该类被声明为分部类,那么您可以通过另一个分部类添加方法,即使它位于另一个程序集 (DLL) 中。
但是,同样,该类最初必须声明为部分类才能起作用。
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.