2016-12-13 42 views
-2

C#7有一个新特性,它允许我们轻松定义元组,所以我们可以轻松地处理包含多个值的结构。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 { } 

这个例子不起作用,因为firstsecondDerived类型。如果我让他们的类型Base这工作正常。

回答

7

这是我自己愚蠢的错误。我忘了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}"); 
    }