尝试在c#中设置作为类属性的数组值时出错

时间:2013-11-13 17:56:48

标签: c#

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];  
};

1 个答案:

答案 0 :(得分:5)

此处的问题是您使用的是班级名称VenueMappings,但您应该使用变量venueMappings。您可以通过类名引用静态属性和方法,但是您只能通过实例引用实例属性和方法。

替换

VenueMappings.venues[0] = venue1;

venueMappings.venues[0] = venue1;