我正在创建一个带有一些可重用代码的C#库,并试图在方法中创建一个方法.我有这样的方法:
public static void Method1()
{
// Code
}
Run Code Online (Sandbox Code Playgroud)
我想做的是:
public static void Method1()
{
public static void Method2()
{
}
public static void Method3()
{
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以选择Method1.Method2或者Method1.Method3.很显然,编译器对此并不满意,非常感谢任何帮助.谢谢.
Ray*_*Ray 95
如果使用嵌套方法,则表示只能在该方法中调用的方法(如在Delphi中),您可以使用委托.
public static void Method1()
{
var method2 = new Action(() => { /* action body */ } );
var method3 = new Action(() => { /* action body */ } );
//call them like normal methods
method2();
method3();
//if you want an argument
var actionWithArgument = new Action<int>(i => { Console.WriteLine(i); });
actionWithArgument(5);
//if you want to return something
var function = new Func<int, int>(i => { return i++; });
int test = function(6);
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 48
这个答案是在C#7问世之前写的.使用C#7,您可以编写本地方法.
不,你做不到.您可以创建一个嵌套类:
public class ContainingClass
{
public static class NestedClass
{
public static void Method2()
{
}
public static void Method3()
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你打电话:
ContainingClass.NestedClass.Method2();
Run Code Online (Sandbox Code Playgroud)
要么
ContainingClass.NestedClass.Method3();
Run Code Online (Sandbox Code Playgroud)
我不会推荐这个.通常,使用公共嵌套类型是个坏主意.
你能告诉我们更多关于你想要实现的目标吗?可能有更好的方法.
Zee*_*han 43
是的,当C# 7.0发布时,本地功能将允许您这样做.您将能够在方法内部拥有一个方法:
public int GetName(int userId)
{
int GetFamilyName(int id)
{
return User.FamilyName;
}
string firstName = User.FirstName;
var fullName = firstName + GetFamilyName(userId);
return fullName;
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*kin 25
您可以使用完整代码在方法中定义委托,并根据需要调用它们.
public class MyMethods
{
public void Method1()
{
// defining your methods
Action method1 = new Action( () =>
{
Console.WriteLine("I am method 1");
Thread.Sleep(100);
var b = 3.14;
Console.WriteLine(b);
}
);
Action<int> method2 = new Action<int>( a =>
{
Console.WriteLine("I am method 2");
Console.WriteLine(a);
}
);
Func<int, bool> method3 = new Func<int, bool>( a =>
{
Console.WriteLine("I am a function");
return a > 10;
}
);
// calling your methods
method1.Invoke();
method2.Invoke(10);
method3.Invoke(5);
}
}
Run Code Online (Sandbox Code Playgroud)
在类中使用嵌套类总是可以选择从外部看不到并调用其方法,例如:
public class SuperClass
{
internal static class HelperClass
{
internal static void Method2() {}
}
public void Method1 ()
{
HelperClass.Method2();
}
}
Run Code Online (Sandbox Code Playgroud)
从C#7.0开始,你可以这样做:
public static void SlimShady()
{
void Hi([CallerMemberName] string name = null)
{
Console.WriteLine($"Hi! My name is {name}");
}
Hi();
}
Run Code Online (Sandbox Code Playgroud)
这被称为本地功能,这正是您所寻找的.