C#在方法中是否有方法概念?

6 .net c# methods delegates

我一直在使用javascript,我在函数内部使用了很多函数.我在C#中试过这个,但似乎它们不存在.如果我有以下内容:

public abc() {


}
Run Code Online (Sandbox Code Playgroud)

如何编写一个d()只能从方法内部调用方法的方法abc()

Rud*_*ser 5

我不担心在方法级别上限制访问方法但是更多的类级别,您可以private用来限制方法对该特定类的访问.

另一种方法是使用lambdas /匿名方法,或者如果你使用C#4.0,Action/ Tasks在你的方法中创建它们.

使用委托(C#1/2/3/4)为您的特定示例(包括我需要一个可以接受字符串参数并返回字符串的操作?)的匿名方法的示例将是这样的:

delegate string MyDelegate(string);

public void abc() {
    // Your code..

    MyDelegate d = delegate(string a) { return a + "whatever"; };
    var str = d("hello");
}
Run Code Online (Sandbox Code Playgroud)

..使用C#3/4:

public void abc() {
    // Your code..

    Func<string, string> d = (a) => { return a + "whatever"; };
    var str = d("hello");
}
Run Code Online (Sandbox Code Playgroud)

..通过private方法使用更理想的解决方案:

private string d(string a)
{
    return a + "whatever";
}

public void abc()
{
    // Your code..

    var str = d("hello");
}
Run Code Online (Sandbox Code Playgroud)

基于你对另一个答案的评论:我只想在方法的底部有这个,然后从一些早期的代码中调用它.

这是不可能的,您需要使用委托或方法为您的方法定义变量Actions,因此需要在调用它时完全初始化它.那么您就无法在方法的底部定义它.一个更好的选择是简单地private在你的类上创建一个新方法并调用它.