object reference is required for the non-static field, method, or property
我的代码中出现上述错误,我无法弄清楚原因(有许多类似的问题,但我读过的所有内容似乎都与我有关)。
class Program
{
static void Main(string[] args)
{
VenueMappings venueMappings = new VenueMappings();
var venue1 = new Venue
{
ExtEventNo = 1,
UsiVenue = "building1",
};
VenueMappings.venues[0] = venue1;
}
}
public struct Venue
{
public int ExtEventNo;
public String UsiVenue;
};
public class VenueMappings
{
public Venue[] venues = new Venue[2];
};
答案 0 :(得分:5)
此处的问题是您使用的是班级名称VenueMappings
,但您应该使用变量venueMappings
。您可以通过类名引用静态属性和方法,但是您只能通过实例引用实例属性和方法。
替换
VenueMappings.venues[0] = venue1;
与
venueMappings.venues[0] = venue1;