簡體   English   中英

C# 11 - 通過將 IAdditionOperators 添加到此方法,我們獲得了什么?

[英]C# 11 - What have we gained by adding IAdditionOperators to this method?

我剛剛將 Visual Studio 2022 升級到 .NET7,其中包括 C# 11。我有興趣嘗試新的static 抽象接口方法,因此按照那里的教程進行操作。

本文介紹了如何定義使用新的IAdditionOperators<>接口的PointTranslation記錄...

public record Translation<T>(T XOffset, T YOffset) where T : IAdditionOperators<T, T, T>;

public record Point<T>(T X, T Y) where T : IAdditionOperators<T, T, T> {
  public static Point<T> operator +(Point<T> left, Translation<T> right) =>
    left with { X = left.X + right.XOffset, Y = left.Y + right.YOffset };
}

這使您能夠做到這一點......

var pt = new Point<int>(3, 4);
var translate = new Translation<int>(5, 10);
var final = pt + translate;

接下來說...

您可以通過聲明這些類型實現適當的算術接口來提高此代碼的可重用性。 要做的第一個更改是聲明Point<T, T>實現IAdditionOperators<Point<T>, Translation, Point> interface. The Point type makes use of different types for operands and the result. The interface. The type makes use of different types for operands and the result. The類型已經實現了帶有該簽名的運算符 + ,因此只需將接口添加到聲明中即可:

public record Point<T>(T X, T Y) : IAdditionOperators<Point<T>, Translation<T>, Point<T>>
    where T : IAdditionOperators<T, T, T>

我很難理解這一點。 在添加額外的實現部分之前,您可以將Translation添加到Point ,如上面的代碼所示,並如我引用的段落的最后一行中所述。

問題 1:通過將: IAdditionOperators<Point<T>, Translation<T>, Point<T>>插入到Point的聲明中,我們得到了什么?

問題 2:這如何使代碼更可重用? 它似乎沒有啟用任何以前不起作用的東西。

之后文章繼續討論附加身份特征,這似乎是一個單獨的點。

有什么可以解釋我在這里失蹤的嗎?

例如,它允許定義以下通用方法並將其與Point<T>Translation<T>一起使用(即對加法操作進行通用抽象):

public static T AddAll<T, TOther>(T t, List<TOther> c) where T : IAdditionOperators<T, TOther, T>
{
    foreach (var item in c)
    {
        t = t + item;
    }

    return t;
}

和用法(可能由於接口介紹):

Point<int> p = AddAll(new Point<int>(1, 1), new List<Translation<int>>());

暫無
暫無

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

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