2016-12-13 5 views
-2

C#7にはタプルを簡単に定義できる新機能があり、複数の値を含む構造で簡単に作業できます。C#7:タプルとジェネリックス

タプルをジェネリック型制約などとして使用する方法はありますか?例えば、私は次のメソッドを定義しようとしました:

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

} 

私は、この特定の例はかなり無意味です実現が、私は別の由来タイプを含むタプルを有することが有用であろう他のシナリオを想像しますタイプ:firstsecondはタイプDerivedであるため

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 { } 

この例では動作しません。私がそれらをタイプBaseにすると、これはうまく動作します。

答えて

7

これは私の愚かな間違いでした。

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}"); 
    } 
これがそうであるように

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

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

:私はこれが正常に動作します

BaseDerived間の継承を忘れてしまいました...

関連する問題