简体   繁体   English

命名空间内的方法c#

[英]Methods inside namespace c#

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? 例如,如果我有两个完全相同的方法并且应该在我的所有C#项目中使用,有没有办法只需要将这些函数放入一个dll中,然后在顶部说“使用myTwoMethods”并开始使用方法而不声明类?

Right now, I do: MyClass.MyMethod(); 现在,我做:MyClass.MyMethod();

I want to do: MyMethod(); 我想做:MyMethod();

Thanks, Rohit 谢谢,罗希特

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. 2015年更新:不,你不能在C#中创建“自由函数”,但从C#6开始,你将能够在不提及类名的情况下调用静态函数。 C# 6 will have the "using static" feature allowing this syntax: C#6将具有“using static”功能,允许使用以下语法:

static class MyClass {
     public static void MyMethod();
}

SomeOtherFile.cs: SomeOtherFile.cs:

using static MyClass;

void SomeMethod() {
    MyMethod();
}

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();

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. 根据建议使用扩展方法,您可以使该方法成为System.Object的扩展方法,所有类都派生自该方法。 I would not advocate this, but pertaining to your question this may be an answer. 我不会提倡这个,但是关于你的问题,这可能是一个答案。

namespace SomeNamespace
{
    public static class Extensions
    {
      public static void MyMethod(this System.Object o)
      {
        // Do something here.
      }
    }
}

You could now write code like MyMethod(); 你现在可以编写类似MyMethod();代码MyMethod(); anywhere you have a using SomeNamespace; 你在任何地方using SomeNamespace; , unless you are in a static method (then you would have to do Extensions.MyMethod(null) ). ,除非你是一个静态方法(然后你必须做Extensions.MyMethod(null) )。

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. 这使您可以轻松地向现有对象添加额外功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM