簡體   English   中英

從 C# 中的靜態方法實例化類

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM