Understanding classes?

本文关键字:classes Understanding | 更新日期: 2023-09-27 18:26:33

为什么这个部分代码没有运行并显示消息"不能用实例引用访问,而是用类型名限定它"?请给我解释一下。

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {         
       public Form1()
        {
        }
       public class Report //my public class
        {
            public static double[] KwotaZ = new double[10];
            public static double[] KwotaNa = new double[10];
            public static string[] WalutaNa = new string[10];
            public static string[] WalutaZ = new string[10];
            public static int IlOperacji = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Report raport2 = new Report(); //create new object class Report
            raport2.KwotaZ[raport2.IlOperacji] = 213.3; //this wrong part code why???
            Konwerter();
        }
    }
}

Understanding classes?

您使用的是带有实例的静态变量。只有一个静态变量。

所以你应该像一样静态使用它

Report.KwotaZ[Report.IlOperacji] = 213.3;

或者将它们定义为这样的实例变量(没有static关键字)

public double[] KwotaZ = new double[10];
public int IlOperacji = 0;

KwotaZIlOperacjistatic字段,因此访问它们的语法不是instance.fieldName,而是TypeName.fieldName,就像中一样

Report.KwotaZ[Report.IlOperacji] = 213.3;

这将允许程序进行编译,但这可能不是您想要的。更有可能的是,您应该将static字段转换为实例属性:

public class Report //my public class
{
    // Only showing two properties here; do the rest in the same manner
    public double[] KwotaZ { get; set; }
    public double[] KwotaNa = { get; set; }
    public Report()
    {
        this.KwotaZ = new double[10];
        this.KwotaNa = new double[10];
    }
}

问题出在"Report"类中的"static"关键字上。"static"表示变量只有一个副本。例如,即使您创建了"Report"类的5个实例,它们也将具有相同的"KwotaZ"值。

您可能想要的是删除"static"关键字。这样,"Report"的每个实例都将有自己版本的变量。