0

使用此代码:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("saturnisko: {0}", UkladSloneczny.saturn.mass);
        }
    }
    public class UkladSloneczny
    {
        private Saturn sat;

        public UkladSloneczny(Saturn sat)
        {
            this.sat = sat;
        }
        public Saturn saturn
        {
            get { return this.sat; }
        }
    }
    public class Saturn
    {
        private int masa;
        public Saturn() { masa = 0; }
        public int mass
        {
            get { return this.masa; }
        }
    }  

为什么我收到这样的错误:

Error   1   An object reference is required for the non-static field, method, or property 'ConsoleApplication1.UkladSloneczny.saturn.get'

?

4

4 回答 4

1

我假设你在这里得到它:Console.WriteLine("saturnisko: {0}", UkladSloneczny.saturn.mass);

UkladSloneczny不是静态类,所以你不能这样称呼它。您需要将其设为静态或创建new该类的实例,然后调用yourClassInstance.saturn.mass.

于 2013-05-29T15:28:39.050 回答
1

如果class,method或者property不是static那么你必须object在内存中实例化它才能对它做任何事情,否则object就是null

所以要么:

public static class UkladSloneczny
{
    private static Saturn sat;

    public UkladSloneczny(Saturn sat)
    {
        sat = sat;
    }
    public static Saturn saturn
    {
        get { return sat; }
    }
}

或者

new UkladSloneczny().saturn.mass
于 2013-05-29T15:30:03.050 回答
0

您需要为 UkladSloneczny 创建一个对象:

class Program
{
    static void Main(string[] args)
    {
        UkladSloneczny instance = new UkladSloneczny(new Saturn());
        Console.WriteLine("saturnisko: {0}", instance.saturn.mass);
    }
}

或者你可以将土星的质量设为静态属性:

class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("saturnisko: {0}", Saturn.mass);
    }
}

public class Saturn
{
    private static int masa = 0;
    public Saturn() {  }
    public static int mass
    {
        get { return masa; }
    }
}  
于 2013-05-29T15:29:37.807 回答
0

您需要从 UkladSloneczny 的实例中调用它,如下所示:

class Program
{
    static void Main(string[] args)
    {
        Saturn saturn = new Saturn();
        UkladSloneczny ukladSloneczny = new UkladSloneczny(saturn);
        Console.WriteLine("saturnisko: {0}", ukladSloneczny.saturn.mass);
    }
}
于 2013-05-29T15:31:05.667 回答