静态字段问题
我试图理解字段的获取和设置属性,并遇到这个问题,有人可以向我解释为什么我必须将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您在静态上下文中使用该字段,所以在本例中使用方法
public
static
void Main
。由于您的 Program 类只是静态运行,因此没有实例,因此您无法访问任何实例成员。Because you were using the field in a static context, in this case the method
public
static
void Main
. Since yourProgram
class just runs statically there is no instance and therefore you can't access any instance members.因为它是在静态方法中使用的
because it is used in a static method
由于
Main
是静态的,因此您无法从其外部访问非静态实例。Since
Main
is static, you cannot access non-static instances from outside of it.