- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我“偶尔”发现 C# Tuple
很有用,尽管它们有不足之处。
在这些时候,有理由涉足大型 元组
而不是最初显而易见的方法,例如创建特定的类或结构或一般的类,例如类树。
它们包括能够在更多地方/范围内定义 Tuple
。通常在更局部和/或临时范围内,例如在需要的地方和在其他地方不可见的内部函数中,或者作为返回类型,甚至在数组定义中。 Tuple
在某些方面也比普通类和具有(实例化?)嵌套类的类更小。有时,虽然通常是一个弱点,但即使像 Tuple
的成员被自动命名为 Item1
Item2
等这样的数据结构也可能是更可取。
或者更多关于优雅的问题,请参见上面的“动机”。
请参阅此伪 C# 代码:
var t = new Tuple<
Tuple<float, float>,
Tuple<
Tuple<box, box, UInt16>,
Tuple<float, float, float, float>>>
((1.5, 1.5), (
(new box(2, 2), new box(3, 2), 4),
(1.5, 1.8, 1.6, 1.8)));
但是如下面的实际代码所示,所需的类型名称重复随节点/成员的数量呈超线性增长。
var t = new Tuple<
Tuple<float, float>,
Tuple<
Tuple<Box, Box, UInt16>,
Tuple<float, float, float, float>>>
(new Tuple<float, float>(1.5, 1.5),
new Tuple<Tuple<box, box, UInt16>, Tuple<float, float, float, float>>(
new Tuple<box, box, UInt16>(new box(2, 2), new box(3, 2), 4),
new Tuple<float, float, float, float>(1.5, 1.8, 1.6, 1.8)));
nodes: 14
that are leaves: 8
types stated in first example: 14
types stated in the C-Sharp code: 38
If all leaves were classes, like `box`: 45
In a 31 node, 16 leaf, binary tree: 113
随着尺寸的增加,情况会变得更糟,到目前为止是 3.6 倍,想象一下这行代码:
byte byte byte byt count = 4;
有没有办法避免这种类型规范的重复?
最佳答案
如果你只是想避免多次重新输入类型名称,你可以使用 Tuple.Create
:
var t =
Tuple.Create(
Tuple.Create(1.5, 1.5),
Tuple.Create(
Tuple.Create(new box(2, 2), new box(3, 2), (ushort)4),
Tuple.Create(1.5, 1.8, 1.6, 1.8)));
请注意,this 将在可能的情况下使用类型推断,因此如果您需要生成一个 Tuple
,该 Tuple
使用无法直接从参数推断的类型(例如基类型或 ushort
在 4
文字的情况下),您必须进行一些有意的转换或在对 Tuple.Create
的调用中显式指定类型。
不过,有时您必须拼出整个类型名称,例如,在类型成员或方法签名中。在这种情况下,您可以使用 C# 的一个经常被忽视的功能,type alias :
using MyTuple = Tuple<Tuple<float, float>, Tuple<Tuple<box, box, UInt16>, Tuple<float, float, float, float>>>;
...
public class MyClass
{
public MyTuple MyFunc(MyTuple foo, MyTuple bar) { ... }
}
如果没有别名,上面显示的方法的签名将绝对可怕。当然,您也可以随意混合和匹配别名,这意味着复杂的通用类名称可以分解为越来越简单的形式,直到它们变得更易于管理。
但是,我通常仍然建议尽可能使用适当设计的类。
关于c# - 如何避免使用大型 C# 元组加速过度类型化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20875550/
我正在开发适用于 Wordpress 的 PSD,并面临着根据颜色过度对齐背景图像或相反的问题。 在桌面上一切都很好,但在移动设备上背景图像变小了(我使用了 background-size: 100%
在标准 Modelica 流体流量源中,通常指定流量或压力。例如,以下边界设置(P 表示压力边界,F 表示流量边界)通常会围绕管道组件: P - 管道 - P F - 管道 - P 但是,有时在同一侧
我正处于设计基于 Azure 的应用程序的早期阶段。考虑到我可能预期的需求的变化性,Azure 吸引我的地方之一是它的可扩展性。因此,我试图保持事物松散耦合,以便我可以在需要时添加实例。 我看到的关于
我与 Xcode 4 dot notation code sense problem 正好相反!点符号的代码完成不仅显示属性,还显示我的方法(在每个完成的左侧标记 P 或 M 分别指示它是属性还是方法
我是一名优秀的程序员,十分优秀!