我有一个元组:
var a = new Tuple<int, int, int>(1,2,3);
我的问题是:
是否有一种方法(通过///备注
或其他方式)来向对象类型添加简短描述?
前三个int's可能让人感到困惑...
我怎么知道item1是指“年龄”而不是“手指数量”?
不行。 Tuple
类只是在方法内部使用的,如果你想将数据公开,应该定义一个class
或struct
,并为每个值定义属性。
但是,如果你想给你的值赋予有意义的名称,可以使用匿名类型。这些类型被限制只能在方法内部使用。
var a = new { Name = "ABC", Age = 33, NumberOfFingers = 10 };
int age = a.Age;
编辑: 如果你坚持想要从你的方法返回一个元组,那么我的建议是在方法返回值的文档中解释其结构。
/// <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>
中。
public Tuple<int,int> myFunc(){}。
- Royi NamirMyClass
的类,以及名为MyProperty1
、MyProperty2
等的属性一样。 - Douglas不,这是不可能的 - 你无法记录传递的参数。
这是使用元组的一个巨大劣势之一 - 值的含义相当不透明。
我建议编写一个有意义的类/结构体并使用它。
public class Program
{
private record class Person(string Name, int Age, int Fingers);
public static void Main()
{
Person a = new("Peter", 36, 10);
}
}