静态方法——这是通常的行为吗?

发布于 2024-11-11 03:12:51 字数 792 浏览 2 评论 0原文

对静态方法有一个小疑问。

文档说“静态方法无法访问实例成员变量或静态方法和属性只能访问静态字段和静态事件,因为它在创建实例之前就已执行”。因此,下面的代码无法编译,

class staticclass
{
    int a = 20; //Private member

    public static void staticmethod()
    {
        Console.WriteLine("Value Of Instance member variable is: {0}",a);  // Error
    }

}

但我们也知道,在静态方法中我们可以创建同一类的实例。

因此,稍微更改一下上面的代码,我可以在静态方法中访问实例变量。

class staticclass
{
    int a = 20; //PRivate Memeber

    public static void staticmethod()
    {
        staticclass sc = new staticclass(); 
        Console.WriteLine("Value Of Instance member variable is: {0}",sc.a);  
    }

}

此编译正常并显示结果实例成员变量的值是:20

这是正常行为吗?或者我无法正确理解它?

我的意思是,如果是这种情况,那么语句如何保持正确的静态方法只能访问静态字段

谢谢。

Have a small doubt with static method.

Documentation says that "Static method can't access instance member variable OR static methods and properties can only access static fields and static events since it's gets executed much before an instance is created". So, the below code fails to compile

class staticclass
{
    int a = 20; //Private member

    public static void staticmethod()
    {
        Console.WriteLine("Value Of Instance member variable is: {0}",a);  // Error
    }

}

But we also know that, inside a static method we can create an instance of the same class.

So, changing the above code a bit I can access the instance variable in static method

class staticclass
{
    int a = 20; //PRivate Memeber

    public static void staticmethod()
    {
        staticclass sc = new staticclass(); 
        Console.WriteLine("Value Of Instance member variable is: {0}",sc.a);  
    }

}

This Compiles fine and displays the result Value Of Instance member variable is: 20.

Is this a normal behavior? OR I am not able to understand it correctly?

I mean, if this the case then How the statements holds true static methods can only access static fields?

Thanks.

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

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

发布评论

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

评论(1

治碍 2024-11-18 03:12:51

您误解了 static 的含义 - 它意味着您只能访问 this 的静态成员。它不限制您访问另一个对象的非静态成员。

您在静态方法中访问的“其他”对象恰好是同一类的实例这一事实并不重要。

You're misunderstanding what static means – it means that you only have access to static members of this. It doesn't restrict you accessing another object's non-static members.

The fact that the "other" object you're accessing in your static method happens to be an instance of the same class does not matter.

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