簡體   English   中英

C#7:元組和泛型

[英]C# 7: Tuples and generics

C#7具有一項新功能,使我們能夠輕松定義元組,因此我們可以輕松地使用包含多個值的結構。

有什么方法可以將元組用作通用類型約束或類似類型? 例如,我嘗試定義以下方法:

public void Write<T>(T value)
    where T : (int x, int y)
{

}

我意識到這個特定的例子是毫無意義的,但是我想象在其他情況下,有一個元組包含從另一種類型派生的類型會很有用:

static void Main(string[] args)
{
    var first = new Derived();
    var second = new Derived();

    var types = (t: first, u: second);
    Write(types);

    Console.ReadLine();
}


public static void Write((Base t, Base u) things)
{
    Console.WriteLine($"t: {things.t}, u: {things.u}");
}

public class Base { }
public class Derived { }

此示例無效,因為firstsecond的類型為Derived 如果我將它們設為Base類型,則效果很好。

這是我自己的愚蠢錯誤。 我忘了BaseDerived之間的繼承...

這工作正常:

    public static void Write((Base t, Base u) things)
    {
        Console.WriteLine($"t: {things.t}, u: {things.u}");
    }

    public class Base { }
    public class Derived : Base { }

就像這樣:

    public static void Write<T>((T t, T u) things)
    {
        Console.WriteLine($"t: {things.t}, u: {things.u}");
    }

和這個:

    public static void Write<T>((T t, T u) things)
        where T : Base
    {
        Console.WriteLine($"t: {things.t}, u: {things.u}");
    }

暫無
暫無

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

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