问题
Is there any way to call a function that is inside of a namespace without declaring the class inside 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?
Right now, I do: MyClass.MyMethod();
I want to do: MyMethod();
Thanks, Rohit
回答1:
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();
回答2:
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" feature allowing this syntax:
static class MyClass {
public static void MyMethod();
}
SomeOtherFile.cs:
using static MyClass;
void SomeMethod() {
MyMethod();
}
回答3:
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.
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)
).
回答4:
Depends on what type of method we are talking, you could look into extension methods:
http://msdn.microsoft.com/en-us/library/bb383977.aspx
This allows you to easily add extra functionality to existing objects.
来源:https://stackoverflow.com/questions/10568254/methods-inside-namespace-c-sharp