前向声明不编译 [英] Forward declaration does not compile

查看:98
本文介绍了前向声明不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我对C#的经验还不是很丰富.第一次,我不得不编写三个相互递归调用的方法.我无法这样做,因为我无法全部声明它们.我在下面做了一个简单的示例代码.考虑方法A,方法B和方法C. MethodC需要调用MethodB; MethodB需要调用MethodA,但是MethodA需要调用MethodC.无论我如何订购这些方法,都需要向前声明.但是此代码无法编译:

Hello,

I am not very experienced with C# yet. For the very first time I had to write three methods calling each other mutually recursively. I failed to do this because I could not declare them all. I made a simple sample code below. Consider MethodA, MethodB and MethodC. MethodC needs to call MethodB; MethodB needs to call MethodA, but MethodA needs to call MethodC. No matter how I order the methods, one needs forward declaration. But this code will not compile:

class Program
{
    static void Main(string[] args)
    {
    }
    void MethodC();
    void MethodA() { /* will call MethodC */ }
    void MethodB() { /* will call MethodA */ }
    void MethodC() { /* will call MethodB */ }
}



错误消息:程序"已使用相同的参数类型定义了一个名为"MethodC"的成员.

我不明白我没有两次定义方法.首先,这只是一个没有身体的宣言;其次,这是带有body的完整方法定义.还有什么人可以发表前瞻性声明?

我做错什么了吗?

现在,我听说C#与C ++相比非常易于编程.也许很容易,因为我什至没有这么简单的C ++功能?也许甚至不允许递归?请告诉我是否有任何解决方法.如果我的简单问题无法解决,那么谁能使用C#?



Error message: ''Program'' already defines a member called ''MethodC'' with the same parameter types.

I don’t understand this. I do not define method twice. In first place this is only a declaration without a body; in second place this is a full method definition with body. How else one can make a forward declaration?

Do I do something wrong?

Now, I heard C# is very easy to program compared to C++. Maybe it is easy because I cannot have even such a simple C++ feature? Maybe even recursion is not allowed? Please tell me if there is any work around. If my simple problem cannot be solved, how can anyone use C#?

推荐答案

C#不需要前向声明.

There is no forward declaration necessary with C#.

class Program
{
   static void Main(string[] args)
   {
      MethodA();
   }

   private static void MethodA()
   {
      Console.WriteLine("MethodA called");
      MethodB();
   }

   private static void MethodB()
   {
      Console.WriteLine("MethodB called");
      MethodC();
   }

   private static void MethodC()
   {
      Console.WriteLine("MethodC called");
   }
}


这篇关于前向声明不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆