我看书看到一句话:静态方法可以访问静态成员变量,静态方法不可以直接访问实例变量可是,我那本书里面有这样一段代码,这个代码也能运行成功。using System;class MyClass
{
void PrintDateAndTime() // Declare the method.
{
DateTime dt = DateTime.Now; // Get the current date and time.
Console.WriteLine( "{0}", dt ); // Write it out.
} static void Main() // Declare the method.
{
MyClass mc = new MyClass();
mc.PrintDateAndTime(); // Invoke the method.
}
}请问,静态方法Main不是访问了本类的实例成员mc.PrintDateAndTime()么??
这个不是和帖子开头我看到的那句话矛盾了,新手求学长学姐们一语戳破!!!静态方法 实例方法
{
void PrintDateAndTime() // Declare the method.
{
DateTime dt = DateTime.Now; // Get the current date and time.
Console.WriteLine( "{0}", dt ); // Write it out.
} static void Main() // Declare the method.
{
MyClass mc = new MyClass();
mc.PrintDateAndTime(); // Invoke the method.
}
}请问,静态方法Main不是访问了本类的实例成员mc.PrintDateAndTime()么??
这个不是和帖子开头我看到的那句话矛盾了,新手求学长学姐们一语戳破!!!静态方法 实例方法
mc.PrintDateAndTime();
如果改成这样呢?
PrintDateAndTime();
所以并不矛盾。
{
DateTime dt = DateTime.Now; // Get the current date and time.
Console.WriteLine( "{0}", dt ); // Write it out.
}加要static才可以调用
多巩固基础先的, 这个是在同一个类中的,Main也是类中的一个方法,改成private在同一个类中当然是在方法中互相调用了,对于静态方法不可以直接访问实例变量这句话,里面已经说了不能直接访问实例变量了,直接的意思就是说不能直接调用实例方法的,然而你在静态Main中初始化了一个类实例,此时类的实例mc就属于Main方法中的局部变量了,这样当然可以通过类的实例来调用实例方法的了
因此可以直接调用class A
{
string b = new string();
}class B
{
A a = new A();
a.b="";
}而非静态的需要实例化以后才可以访问static class A
{
string b = new string();
}class B
{
A.b="";
}a作为一个实例化的A,才可以访问
{
void PrintDateAndTime() // Declare the method.
{
DateTime dt = DateTime.Now; // Get the current date and time.
Console.WriteLine( "{0}", dt ); // Write it out.
} public MyClass mc = new MyClass();
public int mcc = 1234; static void Main() // Declare the method.
{
mc.PrintDateAndTime(); // Invoke the method.
mcc = 3743;
}
}它的“访问实例变量”是这个意思,是指 mc 和 mcc。不是什么 PrintDateAndTime。
但是你在main中如果没有实例该对象那么你是无法直接访问该实例方法的,因为静态方法只能够不存在隐藏的指向实例对象的this指针,所以静态方法只能范围静态变量和静态方法,但是实例方法却没有该限制,这是因为静态变量和方法是属于类级别的,简单说可以认为是所有该类的实例同享的数据