静态字段问题

发布于 2024-08-13 15:34:50 字数 565 浏览 3 评论 0原文

我试图理解字段的获取和设置属性,并遇到这个问题,有人可以向我解释为什么我必须将 int X 字段设置为静态才能使其工作吗?

using System;

namespace ConsoleApplication1
{
    class Program
    {
        public static int X = 30;
        public static void Main()
        {
            var cX = new testme();
            cX.intX = 12;
            Console.WriteLine(cX.intX);
            cX.intX = X;
            Console.WriteLine(cX.intX);
            Console.ReadKey();
        }
    }
    class testme
    {
        public int intX
        {
            get;
            set;
        }
    }
}

im trying to understand the get and set properties for fields, and run in to this issue, can somone explaine to me why i had to make the int X field Static to make this work?

using System;

namespace ConsoleApplication1
{
    class Program
    {
        public static int X = 30;
        public static void Main()
        {
            var cX = new testme();
            cX.intX = 12;
            Console.WriteLine(cX.intX);
            cX.intX = X;
            Console.WriteLine(cX.intX);
            Console.ReadKey();
        }
    }
    class testme
    {
        public int intX
        {
            get;
            set;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

水溶 2024-08-20 15:34:50

因为您在静态上下文中使用该字段,所以在本例中使用方法 publicstaticvoid Main。由于您的 Program 类只是静态运行,因此没有实例,因此您无法访问任何实例成员。

Because you were using the field in a static context, in this case the method publicstaticvoid Main. Since your Program class just runs statically there is no instance and therefore you can't access any instance members.

装纯掩盖桑 2024-08-20 15:34:50

因为它是在静态方法中使用的

because it is used in a static method

青柠芒果 2024-08-20 15:34:50

由于 Main 是静态的,因此您无法从其外部访问非静态实例。

Since Main is static, you cannot access non-static instances from outside of it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文