静态方法——这是通常的行为吗?
对静态方法有一个小疑问。
文档说“静态方法无法访问实例成员变量或静态方法和属性只能访问静态字段和静态事件,因为它在创建实例之前就已执行”。因此,下面的代码无法编译,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您误解了 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.