簡體   English   中英

“=>”是什么意思(在函數/屬性上下文中)?

[英]What does '=>' mean (in functions / property context)?

在開發 Xamarin 應用程序時,我使用 Lambdas 獲得了自動生成的代碼:

public override string this[int position] => throw new NotImplementedException();

public override int Count => throw new NotImplementedException();

=>運算符在這種情況下是什么意思?

感謝 R

這些不是 lambda,它們是Expression-bodied Members

在屬性的上下文中,這些基本上是簡化為單個表達式(而不是整個語句)的屬性的 getter。

這個:

public override int Count => throw new NotImplementedException();

相當於:

public override int Count {
    get { throw new NotImplementedException(); }
}

正如@sweeper 在您的示例中所說,它們與 lambda 表達式無關,因為它們是表達式主體運算符(在 C# 6 中引入並在 7 中擴展)。 不過,它也用於表示 lambda 表達式,因此它的用法有兩種。

有關=>運算符的每種用法的更多信息,請參見此處; https://learn.microsoft.com/en-us/do.net/csharp/language-reference/operators/lambda-operator

首先,讓我們澄清一下=>運算符目前在兩種不同的上下文中使用:

  1. Lambda 個表達式。 通常您會在 Linq 中看到它們,例如
    var query = Customers.OrderBy(x => x.CompanyName);

  2. 表達式體函數。 這就是我們這里所擁有的。

為了理解=>的含義,請看下面的簡單示例:

using System;

public class Program
{
    public void Main()
    {
        var obj = new Test();
        obj.Count.Dump();
        obj[7].Dump();
    }


    class Test
    {
        public int Count => 1;
        public string this[int position] => $"2 x {position} = {(2*position)}";
    }
}

傾倒對象(Int32)
1個
轉儲對象(字符串)
2×7 = 14

在 DotNetFiddle 中嘗試

在這里, NotImplementedException代碼,它只是告訴你(開發人員)屬性和索引器沒有實現但應該被實現,被一些 function 取代:

  • Count 是一個只讀屬性,總是返回 1
  • 每當您將[... ]應用於 object 時,都會返回雙倍索引

請注意,在 C# 的早期版本中,您必須編寫:

class Test
{
        public int Count { get { return 1; } }
        public string this[int position] { 
            get { return String.Format("2 x {0} = {1}", 
                                       position, (2*position).ToString()); }}
}

這相當於上面的代碼。 所以本質上,在 C#7 中,您必須輸入更少的代碼才能獲得相同的結果。

暫無
暫無

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

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