![](/img/trans.png)
[英]C#: How do I call a static method of a base class from a static method of a derived class?
[英]Class instancing from a static method in C#
我有一个简单的问题。 我知道必须首先初始化类的对象才能在 C# 中使用该(非静态)类。
所以(我认为)这段代码是这样做的:
namespace ConsoleApp10
{
class Program
{
public class Person
{
public string Name;
public void Introduce0()
{
Console.WriteLine("My name is " + Name + ".");
}
}
static void Main(string[] args)
{
var person0 = new Person();
person0.Name = "Marry";
person0.Introduce0();
Console.ReadKey();
}
}
}
结果是:
我叫玛丽。
然后我尝试用静态方法做同样的事情:
namespace ConsoleApp10
{
class Program
{
public class Person
{
public string Name;
public void Introduce0()
{
Console.WriteLine("My name is " + Name + ".");
}
public static Person Introduce1(string str0)
{
var temp0 = new Person();
temp0.Name = str0;
temp0.Introduce0();
return temp0;
}
}
static void Main(string[] args)
{
var person0 = Person.Introduce1("Marry");
Console.ReadKey();
}
}
}
结果和预期的一样:
我叫玛丽。
然后我在Main方法中添加了两段代码:
static void Main(string[] args)
{
var person0 = Person.Introduce1("Marry");
person0.Name = "Sarah";
person0.Introduce0();
Console.ReadKey();
}
结果是:
我叫玛丽。
我的名字是撒拉。
所以,这里是我的问题:
在最后一个示例中,为什么我不必初始化Person对象来访问Name字段和Introduce0方法? 访问静态方法是否意味着自动初始化? 还是因为Introduce1方法中有一个Person对象初始化( temp0 )?
还是因为
Introduce1
方法中有一个 Person 对象初始化(temp0)?
对,就是这样。 Introduce1
是一个静态方法,这意味着您可以在不先创建Person
对象的情况下调用它。
然后,在Introduce1
,创建一个新的Person
对象,该对象随后可用于调用Person
实例方法,例如Introduce0
。
请注意,您的代码在功能上等同于
static void Main(string[] args)
{
var temp0 = new Person();
temp0.Name = "Marry";
temp0.Introduce0();
var person0 = temp0;
person0.Name = "Sarah";
person0.Introduce0();
Console.ReadKey();
}
这是第二个原因:“是不是因为 Introduce1 方法中有一个 Person 对象初始化(temp0)?”。 您正在初始化从 Person.Introduce1 返回的 Person 对象。 类中的方法返回该类的实例是完全有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.