命名空间 c# 中的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10568254/
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
Methods inside namespace c#
提问by rkrishnan2012
Is there any way to call a function that is inside of a namespace without declaring the class inside c#.
有什么方法可以调用命名空间内的函数而不在 c# 中声明类。
For Example, if I had 2 methods that are the exact same and should be used in all of my C# projects, is there any way to just take those functions and make it into a dll and just say 'Using myTwoMethods' on top and start using the methods without declaring the class?
例如,如果我有 2 个完全相同的方法并且应该在我的所有 C# 项目中使用,有没有什么方法可以将这些函数放入一个 dll 中,然后在顶部说“使用 myTwoMethods”并开始使用方法而不声明类?
Right now, I do: MyClass.MyMethod();
现在,我这样做: MyClass.MyMethod();
I want to do: MyMethod();
我想做: MyMethod();
Thanks, Rohit
谢谢,罗希特
采纳答案by David Anderson
You can't declare methods outside of a class, but you can do this using a static helper class in a Class Library Project.
您不能在类之外声明方法,但可以使用类库项目中的静态帮助程序类来实现。
public static class HelperClass
{
public static void HelperMethod() {
// ...
}
}
Usage (after adding a reference to your Class Library).
用法(添加对类库的引用后)。
HelperClass.HelperMethod();
回答by box86rowh
Depends on what type of method we are talking, you could look into extension methods:
取决于我们谈论的方法类型,您可以查看扩展方法:
http://msdn.microsoft.com/en-us/library/bb383977.aspx
http://msdn.microsoft.com/en-us/library/bb383977.aspx
This allows you to easily add extra functionality to existing objects.
这使您可以轻松地向现有对象添加额外的功能。
回答by StellarEleven
Following on from the suggestion to use extension methods, you could make the method an extension method off of System.Object, from which all classes derive. I would not advocate this, but pertaining to your question this may be an answer.
按照使用扩展方法的建议,您可以使该方法成为 System.Object 的扩展方法,所有类都从该方法派生。我不提倡这一点,但关于你的问题,这可能是一个答案。
namespace SomeNamespace
{
public static class Extensions
{
public static void MyMethod(this System.Object o)
{
// Do something here.
}
}
}
You could now write code like MyMethod();anywhere you have a using SomeNamespace;, unless you are in a static method (then you would have to do Extensions.MyMethod(null)).
您现在可以像MyMethod();拥有 的任何地方一样编写代码using SomeNamespace;,除非您使用的是静态方法(那么您必须这样做Extensions.MyMethod(null))。
回答by Asik
Update for 2015: No you cannot create "free functions" in C#, but starting with C# 6 you'll be able to call static functions without mentioning the class name. C# 6 will have the "using static" featureallowing this syntax:
2015 年更新:不,您不能在 C# 中创建“自由函数”,但从 C# 6 开始,您将能够在不提及类名的情况下调用静态函数。C# 6 将具有“使用静态”功能,允许使用以下语法:
static class MyClass {
public static void MyMethod();
}
SomeOtherFile.cs:
SomeOtherFile.cs:
using static MyClass;
void SomeMethod() {
MyMethod();
}

