简体   繁体   English

C#中的可读性和元组

[英]Readability and tuples in C#

Tuples are nice for expressing whole-values. 元组很适合表达整个值。 But it has a penalty on readability, 'Item1' and 'Item2' is not so intuitive. 但它的可读性受到了惩罚,“Item1”和“Item2”并不那么直观。 To improve the latter I introduced a class-alias like below. 为了改进后者,我引入了一个类别名,如下所示。 I was wondering if someone got a better solution. 我想知道是否有人有更好的解决方案。 It still needs a 'dedicated' class anyway. 无论如何,它仍然需要一个“专用”课程。 The example below is naïve, it just points out the problem. 下面的例子是天真的,它只是指出了问题。

enum Unit { Celsius, Fahrenheit }
class Temperature: Tuple<decimal, Unit>
{
        public decimal Value
        {
            get { return Item1; }
        }

        public Unit
        {
            get { return Item2; }
        }

        public Temperature(decimal item1, Unit item2) 
         : base(item1, item2)
        {
    }
}

// pseudo
var temp = new Temperature(37, Unit.Celsius);
temp.Item1 == temp.Value == 37;
temp.Item2 == temp.Unit == Unit.Celsius;

What you've done above is basically create a class with two read-only properties, they just happen to use Tuple as a backing store. 你上面所做的基本上是创建一个具有两个只读属性的类,它们碰巧使用Tuple作为后备存储。

The problem you highlight is not one the Tuple aims to fix. 你强调的问题不是元组旨在解决的问题。 Tuple is there to provide a generic construct for wrapping values in to an object where defining a class is deemed too much effort. 元组在那里提供了一个通用的构造,用于将值包装到一个对象中,其中定义一个类被认为是太费力。 I don't personally rate them and limit them to within a method scope, however anonymous types are better suited - I certainly wouldn't want a return type of Tuple for the exact reason you're highlighting. 我没有亲自评价它们并将它们限制在方法范围内,但匿名类型更适合 - 我当然不希望返回类型的元组,因为你突出显示的确切原因。

If you want to have a read/write class with named properties, create a class (or struct). 如果要使用带有命名属性的读/写类,请创建一个类(或结构)。

C# 6 is going to introduce a new syntax for "primary constructors" which will substantially simplify classes such as your class Temperature . C#6将为“主要构造函数”引入一种新语法,它将大大简化诸如类等class Temperature

For example: 例如:

public sealed class Temperature(decimal value, Unit unit)
{
    public decimal Value { get; } = value;
    public Unit    Unit  { get; } = unit;
}

In the future, you should be able to use that approach instead. 将来,您应该能够使用该方法。 (I'm not going to debate whether that's a good thing or not though!) (我不打算辩论这是否是好事!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM