C# - 此语句在 Visual C# 中的用途是什么?

标签 c# object initialization

我想我有一个相当基本的问题。我不是想浪费你的时间,但我只是不知道要谷歌什么才能得到好的答案。我的问题与对象初始化有关。以 Head First C# 书中的以下示例为例:

using System;
using etc...

namespace Bees
{
   public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Queen queenie = new Queen(workers, Report); //Queen is a created class
        }
        Queen queenie; //This is the line I'm curious about

        private void assignButton_Click(object sender, EventArgs e)
        {
            Report.AppendText(queenie.AssignWork(comboBox1.SelectedItem.ToString(), (int)shifts.Value));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            queenie.WorkNextShift();
        }
...

如果我已经通过 Queen queenie = new Queen(...); 实例化了一个 Queen 对象,那么 Queen queenie 这行有什么用,以及它的范围是什么?我在这里误解了什么关键概念?

最佳答案

这看起来像是代码中的错误。大概是这个意思:

public Form1()
{
    InitializeComponent();
    queenie = new Queen(workers, Report);
}

Queen queenie; //This is where the reference to the constructed Queen is stored

Queen queenie; 声明了一个 Queen 类型的字段,该字段可从实例的所有方法访问,但不能从类外部访问。

如果您不确定其中一些术语的含义,我建议您遵循更温和的教程:

或者,如果您已经超出了当年的图书预算,那么浏览一些免费的在线文档:

关于C# - 此语句在 Visual C# 中的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10776844/

相关文章:

ios - 快速自定义类初始化

c - 未初始化的变量如何获得随机值?

c++ - C++中的多维对象数组,我无法初始化它!

javascript - 如何验证日期输入?

javascript - 我怎样才能连接两个对象?

C/Cython : Initial content of an malloc memory allocation

c# - MongoDB - 使用 C# 驱动程序按日期和时间搜索

c# - 替代越来越慢的 Dictionary.Add(Key,Value)?

c# - 如何使用 C# 和 ASP.NET 以 P2P 方式传输多媒体文件?

c# - DbContext 连接字符串和托管服务