C# 中的前向声明

Foward Declarations in C#

真的 喜欢在 class 的开头声明我的所有方法,并希望通过前向声明来实现,然后进一步实现它们。这在 C# 中可行吗?

例如:

private void Test();

private void Test()
{
}

简单的回答不,这是不可能的。 原因是 C# 中没有独立的函数,但是 class 有方法。

一旦您开始使用 C++ 等其他语言,class也不需要方法本身的前向声明。可能 classes 本身需要 C++ 中的前向声明,但由于您在谈论方法,因此比较仍然有效。

底线 a class 完全由其方法按照它们定义的任何顺序定义。

你真的不能在 C# 中做这样的事情。我不确定你为什么真的想要。将声明和定义放在一处,简单易懂

在某些其他语言中需要执行类似的操作,但在 C# 中强制使用该模式可能不是一个好主意。

不,你做不到。您只能像这样声明抽象方法。否则会报错。

我试过了,它给了我

Error   1   'Project.SomeClass.ABC()' must declare a body because it is not marked abstract, extern, or partial

只能这样定义抽象方法,抽象方法只需要重写一个原型即可。 这是有效的:

public abstract void ABC();

前向声明在 C# 中是不可能的 类。只有在接口中并且您的方法是 abstract 时才有可能。允许这样的事情

abstract void Draw();

您可以使用界面来完成

只需定义您的 class 将通过从接口继承来使用的方法。 将此接口视为前向声明和合同的混合体。 类 从接口继承必须实现其所有成员。

public interface iSomeClass
{
    void MyMethod1();
    bool MyBoolMethod();
}


public class MyClass : iSomeClass
{
    public void MyMethod1()
    {
     //...
    }

    public bool MyBoolMethod()
    {
     //...
     return true;
    }
}

是的,你可以做到。或者你可以有点这样做。但是对于这些可能的“解决方案”中的每一个,如果仅出于美观原因请不要使用这些结构。

一个技巧是使用部分 class 和 partial methods

partial class A
{
    partial void OnSomethingHappened(string s);
}

// This part can be in a separate file. 
partial class A
{
    /* Comment out this method and the program 
     will still compile.*/
    partial void OnSomethingHappened(string s)
    {
        Console.WriteLine("Something happened: {0}", s);
    }
}

正如参考文档中强调的那样,它的用途是有限的:

A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time.

The following conditions apply to partial methods:

  • Signatures in both parts of the partial type must match.

  • The method must return void.

  • No access modifiers are allowed. Partial methods are implicitly private.

正如 and 答案中所指出的,可以使用的另一种“有点类似”的结构是接口或纯抽象的声明 class,与您在C++:

public interface IA
{
    int GetTheOneAndOnlyNumber(); 
}

public abstract class AA
{
    protected abstract void OnSomethingHappened(string s);
}

public class A : AA, IA
{
    public int GetTheOneAndOnlyNumber()
    {
        return 42;
    }
    protected override void OnSomethingHappened(string s)
    {
        Console.WriteLine(s);
    }
}

当从一种我们熟悉的语言切换到一种新语言时,我们总会错过一些特定的习语和结构。这并不意味着尝试用新语言中的非惯用结构来模拟它们是明智的。

如果您想在 Visual Studio 中查看代码结构的压缩视图,可以使用 several standard ways,例如对象浏览器和 Class 视图.

如果您搜索并环顾四周,您会发现其他可用的工具可以帮助您快速了解代码的结构。