我可以将ValueTuple传递给需要泛型类型并仍然维护成员变量的方法吗?

Gee*_*_SO 2 c# tuples valuetuple

以下只是一个关于语言本身的问题,我在发布一个更好的方法来构建我的代码之前开始考虑这个问题,但它让我感兴趣.

如果我有这种结构的方法

private void Foo<T>(T bar){
    //do stuff with tuples
}
Run Code Online (Sandbox Code Playgroud)

在不同的类和方法中,我有一个变量

(int first, int second) myTuple = (1,2);
Run Code Online (Sandbox Code Playgroud)

在这个变量的范围内,我可以做类似的事情

var firstValue = myTuple.first;
Run Code Online (Sandbox Code Playgroud)

无论如何,我可以传递myTupleFoo维持元组内元素的命名,以便我可以做类似的事情bar.firstValue

Aka*_* KC 5

通过在类中进行解构实现T,您可以使用元组访问实例字段.您需要在T类中提供解构实现,以便为元组获取正确的值.

您可以通过以下方式解决问题:

  1. T课堂上提供解构实现,假设TTestClass

    public class TestClass
    {
    
        private int _first { get; set; }
    
        private int _second { get; set; }
    
        private int _third { get; set; }
    
        public TestClass(int first, int second, int third)
        {
            _first = first;
            _second = second;
            _third = third;
        }
    
        // Implementation for tuple deconstruct
        public void Deconstruct(out int first, out int second)
        {
            first = _first;
            second = _second;
        }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在您的Foo方法中,您可以通过以下方式访问:

    public class Bar
    {
        public void Foo<T>(T data) where T : TestClass
        {
    
               (int first, int second) = data;
    
               //do stuff with tuples
         }
    }
    
    Run Code Online (Sandbox Code Playgroud)


Pau*_*ado 5

元组值名称不附加到实例,而是附加到函数的变量、参数或返回值。

这是所有有效的 C# 代码:

(int a, string bx) M((int x, string y) p) => p;
// ..
(int i, string s) v1 = (j:1, k:"ome");
(int m, string n) v2 = M(v1);
Run Code Online (Sandbox Code Playgroud)

对于运行时来说,真正重要的是元组的类型(在上面的示例中始终是ValueTuple<int, string>)。这些名称只是为代码读者提供的工具便利。