【问题标题】:C# 7: Tuples and genericsC# 7:元组和泛型
【发布时间】:2017-04-28 17:35:03
【问题描述】:

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 类型,则效果很好。

【问题讨论】:

    标签: c# generics c#-7.0


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2017-08-22
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多