我正在用一些可重用的代码创建一个C#库,并试图在一个方法中创建一个方法。我有一个这样的方法:
public static void Method1()
{
// Code
}我想做的是:
public static void Method1()
{
public static void Method2()
{
}
public static void Method3()
{
}
}然后我可以选择Method1.Method2或Method1.Method3。显然,编译器对此并不满意,任何帮助都是非常感谢的。谢谢。
发布于 2011-11-15 18:44:34
这个答案是在C# 7问世之前写的。在C# 7中,你可以使用
不,你不能这么做。您可以创建一个嵌套类:
public class ContainingClass
{
public static class NestedClass
{
public static void Method2()
{
}
public static void Method3()
{
}
}
}然后你会调用:
ContainingClass.NestedClass.Method2();或
ContainingClass.NestedClass.Method3();不过,我不推荐这样做。通常,拥有公共嵌套类型不是一个好主意。
你能告诉我们更多关于你正在努力实现的目标吗?很可能会有更好的方法。
发布于 2011-11-15 18:46:40
如果您所说嵌套方法是指只能在方法内调用的方法(如在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);
}发布于 2016-08-22 23:10:07
是的,当C# 7.0发布时,Local Functions将允许您这样做。您将能够在方法中拥有一个方法,如下所示:
public int GetName(int userId)
{
int GetFamilyName(int id)
{
return User.FamilyName;
}
string firstName = User.FirstName;
var fullName = firstName + GetFamilyName(userId);
return fullName;
}请注意,C# programming guide不支持public (和类似的修饰符
私有,因为所有局部函数都是私有的,包括访问修饰符,例如
关键字,会生成编译器错误CS0106 "
https://stackoverflow.com/questions/8135050
复制相似问题