为每个Tuple对象添加描述?

问题描述 投票:0回答:4

我有一个元组:

var a = new Tuple<int, int, int>(1,2,3);

我的问题:

有什么方法(通过

/// remark
或其他方式)为对象类型添加简短描述吗?

前 3 个 int's 可能会令人困惑......

我怎么知道 item1 指的是“年龄”而不是“手指数量”?

enter image description here

c# .net .net-4.0
4个回答
12
投票

不。

Tuple
类仅用于方法内部;如果您打算公开数据,您应该为每个值定义一个
class
struct
以及属性。

但是,如果您想为值指定有意义的名称,则可以使用匿名类型。这些是约束(不仅仅是有意)只能在方法内部使用。

var a = new { Name = "ABC", Age = 33, NumberOfFingers = 10 };
int age = a.Age;

Anonymous type

编辑:如果您确信要从方法返回一个元组,那么我的建议是在方法返回值的文档中解释其结构。

/// <summary>
/// Retrieves personal information about the person.
/// </summary>
/// <returns>
/// A tuple containing the following information:
/// <list type="bullet">
/// <item><see cref="Tuple{T1,T2,T3}.Item1"/>: The name of the person.</item>
/// <item><see cref="Tuple{T1,T2,T3}.Item2"/>: The age of the person.</item>
/// <item><see cref="Tuple{T1,T2,T3}.Item3"/>: The number of fingers the person has.</item>
/// </list>
/// </returns>
public Tuple<string, int, int> GetPerson()
{
    return Tuple.Create("ABC", 33, 10);
}

如果您希望它显示在 IntelliSense 中,请将您的解释放在

<summary>
中。


4
投票

不,这是不可能的 - 您无法记录传入的参数。

这是使用

Tuple
的一大缺点 - 值的含义相当不透明。

我建议编写一个具有有意义名称的类/结构并使用它。


0
投票

我知道这是一篇旧帖子,但我认为值得一提,以防不熟悉

tuple
的人偶然发现它,但您现在可以命名
tuple
的字段(请参阅此处)。

我不确定如何在方法的

<summary>
<remarks>
标记中引用它们,但如果将名称添加到方法的返回类型中,代码的其他部分也可以使用它们!


0
投票

我们现在(.NET 6 及更高版本)也可以在此类情况下使用记录,而不是元组或动态类型。

public class Program
{
    private record class Person(string Name, int Age, int Fingers); 
    public static void Main()
    {
        Person a = new("Peter", 36, 10);
    }
}

如果您需要变量名称之外的进一步描述,您还可以将 xml 代码文档添加到这些记录中。

另请参阅:learn.microsoft.com 上的记录

© www.soinside.com 2019 - 2024. All rights reserved.