为什么我的 C# 构造函数无法使用我尝试使用的方法?



也许我误解了构造函数的工作原理,但无论如何,我正在尝试创建一个数组并将其填充到构造函数中。

我有以下代码 -

class ClsDeck
{
    private string[] deck = new string[52];
    private string[] hand = new string[12];
    BuildDeck()
    {
        //lots of code assigning images to each individual element of the "deck" array.
    }
    //many other methods that need to be called by a form.
}

Visual Studio 2012 坚持该方法具有返回类型。我只是简单地在 BuildDeck 方法中添加了"void",错误消失了,但我看到的每个构造函数示例都必须与类同名,并且它是类中唯一的方法。

这甚至不会编译。 BuildDeck()没有返回类型。构造函数名称需要与类名匹配(包括大小写)。将BuildDeck替换为 ClsDeck()

根据定义,构造函数是一个方法,1.) 与类同名,2.)没有返回值。

在上面的例子中,"BuildDeck"不是一个构造函数......它是一个方法,因此必须指定返回类型(如果未返回任何内容,则指定"void")。

如果你想要一个构造函数,请将"BuildDeck"重命名为"ClsDeck"。

实际上缺少类的构造函数。

进行以下更改,您的代码将编译:

class ClsDeck
{
    private string[] deck = new string[52];
    private string[] hand = new string[12];
    public ClsDeck()
    {
        // Place your array initializations here.
    }
    private void BuildDeck()
    {
        //lots of code assigning images to each individual element of the "deck" array. }
        //many other methods that need to be called by a form.
    }
}

这将不起作用或编译。为了实现你想要的,你可以有一个用于ClsDeck的构造函数并调用BuildDeck

class ClsDeck {
    private string[] deck = new string[52];
    private string[] hand = new string[12];
    ClsDeck() { //lots of code assigning images to each individual element of the "deck" array. }
        //many other methods that need to be called by a form.
        BuildDeck();
    }
    private void BuildDeck() {
        //Build your deck
    }
}

最新更新