簡體   English   中英

為什么在使用字段而不是表達式主體屬性時不執行字符串連接?

[英]Why is string concatenation not executed when using a field rather than an expression-bodied property?

為什么以下代碼輸出“STRING_PART_1\STRING_PART_2”

class Program
{
    static void Main(string[] a)
    {
        Console.WriteLine(DummyClass.Property1);
    }
}

internal class DummyClass
{
    public static string Property1 => "STRING_PART_1\\" + Property2;
    public static string Property2 => "STRING_PART_2";
}

但是下面的代碼輸出“STRING_PART_1”?

class Program
{
    static void Main(string[] a)
    {
        Console.WriteLine(DummyClass.Property1);
    }
}

internal class DummyClass
{
    public static string Property1 = "STRING_PART_1\\" + Property2;
    public static string Property2 = "STRING_PART_2";
}

我應該期望使用屬性 ( = ) 而不是表達式=>有什么區別?

這段代碼:

public static string Property1 => "STRING_PART_1\\" + Property2;

相當於:

public static string Property1
{
    get => "STRING_PART_1\\" + Property2;
}

因此,當您訪問此屬性時,將調用 getter(其中調用Property2的 getter)。

這些甚至不是屬性-字段(在您的情況下並不重要):

public static string Property1 = "STRING_PART_1\\" + Property2;
public static string Property2 = "STRING_PART_2";

初始化順序是: Property1然后Property2

當您初始化Property1時, Property2尚未初始化( null ),這就是您輸出的原因。

當您將申報順序更改為:

public static string Property2 = "STRING_PART_2";
public static string Property1 = "STRING_PART_1\\" + Property2;

你會得到想要的結果,因為Property2Property1之前初始化。

當您在使用=時將Property2Property1切換時,它將輸出STRING_PART_1\STRING_PART_2

因此,lambda 表達式忽略了變量的順序,而正常操作則不然。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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