【问题标题】:How can I call local methods from functions in other classes如何从其他类中的函数调用本地方法
【发布时间】:2020-07-02 16:46:09
【问题描述】:

我有两个类,包含形状函数的“Shapes”和主类“Program”

    public static double TriSides(double b, double h)
    {
        var res = b * h;
        return res;
    }

    public static double Circular(double diameter)
    {
        double SemiCirc(double radius)
        {
            return radius;
        }
        return diameter;
    }
}
class Program
{
    public static void Main(String[] arg)
    {
        Console.WriteLine("A program to generate a shape based on user input");

        Thread.Sleep(500);
        Shapes n = new Shapes();
        Console.Write("Number of sides(1 - 4): ");
        Variables.userInput = Console.ReadLine();
        var input = Variables.userInput;
        if (input == "4")
        {
            Shapes.Quadrilaterals(Variables.inputNum, Variables.inputNum);
        }

        else if (input == "3")
        {
            Shapes.TriSides(Variables.inputNum, Variables.inputNum);
        }

        else if (input == "2")
        {
            //The nested function from the "Circular" function is supposed to be called here
        }

        else if(input == "1")
        {
            Shapes.Circular(Variables.inputNum);
        }
        
    }
}

}

我无法从“Shapes”类中的“Circular”方法访问本地方法“SemiCirc”

【问题讨论】:

  • 您是否有特定的理由以这种方式定义 SemiCirc?

标签: c# nested-function


【解决方案1】:

您不能在定义它们的函数之外调用本地方法!

如果您想调用该方法,则不要将其设为本地,将其提升到类级别。

【讨论】:

    【解决方案2】:

    您无法访问该方法,因为它是“循环”方法的私有。

    【讨论】:

      【解决方案3】:

      制作半圆公共方法并将其提升到类级别。截至目前这是私有的,私有不能在课堂外访问。

      【讨论】:

        【解决方案4】:

        没有直接的方法来调用它。 但是你可以利用反射。

        内联是参考代码。通过调试器检索方法名称。

        else if (input == "2")
        {
            //The nested function from the "Circular" function is supposed to be called here
            Type shapesType = typeof(Shapes);
            MethodInfo semiCircMethodInfo = shapesType.GetMethod(
                "<Circular>g__SemiCirc|1_0", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
            var retValue = semiCircMethodInfo.Invoke(null, new[] { (object)6 });
        }
        

        【讨论】:

          【解决方案5】:

          在包含成员中定义的所有局部变量,包括其方法参数,都可以在局部函数中访问。 公开

          【讨论】:

            猜你喜欢
            • 2020-07-29
            • 1970-01-01
            • 1970-01-01
            • 2019-12-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多