[英]C#: Passing a value between classes (Error CS0120)
In the code below I get an error when I try to call the array from an other class. 在下面的代码中,当我尝试从其他类调用数组时出现错误。 What went wrong? 什么地方出了错?
Error CS0120: An object reference is required to access non-static member `learningcsharp.Wall.Ar' (CS0120) 错误CS0120:访问非静态成员“ learningcsharp.Wall.Ar”需要一个对象引用(CS0120)
using System;
namespace learningcsharp
{
public class Wall
{
private int[] _ar;
public int[] Ar
{
get
{
return _ar;
}
set
{
_ar = value;
}
}
public void build()
{
Ar = new int[] { 0, 0, 1, 0, 0 };
}
}
public class Draw
{
public void draw()
{
Console.WriteLine (Wall.Ar[1]); // ERROR CS0120
}
}
class MainClass
{
public static void Main (string[] args)
{
Wall wall = new Wall ();
wall.build ();
Draw draw = new Draw ();
draw.draw ();
}
}
}
You need to pass an instance of Wall to draw method as parameter 您需要传递Wall实例以将方法绘制为参数
public class Draw
{
public void draw(Wall wall)
{
Console.WriteLine (wall.Ar[1]);
}
}
And you can call it like: 您可以这样称呼它:
public static void Main (string[] args)
{
Wall wall = new Wall ();
wall.build ();
Draw draw = new Draw ();
draw.draw (wall);
}
The error litterally explained what to do, but here is a example from Jamie Dixon's post: Object in C# 该错误从字面上解释了该怎么做,但这是杰米·迪克森(Jamie Dixon)的文章中的示例: C#中的对象
This is from the Offical MSDM page: Creating objects/classes I think that is exactly what you need. 这来自“官方MSDM”页面: 创建对象/类我认为这正是您所需要的。
I hope this helps you out. 我希望这能够帮到你。
Good luck 祝好运
Or simply mark array as static: 或简单地将数组标记为静态:
private static int[] _ar;
also with property. 也有财产。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.