问题描述
考虑以下表达式:
new Tuple<int,int>(1,2);
Tuple.Create(1,2);
这两种创建元组的方法有什么区别吗?从我的阅读来看,它似乎比 C++ 中的对象创建(堆与堆栈)更方便.
Is there any difference between these two methods of Tuple creation? From my reading it seems to be more a convenient shorthand than anything like object creation in C++ (heap vs stack).
推荐答案
嗯,这个问题很老了……但我认为我可以做出建设性的贡献.从接受的答案:
Well, this questions is old... but nevertheless I think I may contribute constructively. From the accepted answer:
我想一个好处是,由于您不必使用 Tuple.Create 指定类型,因此您可以存储匿名类型,否则您将无法说出类型是什么
结果是正确的:您可以存储匿名类型...
The consequence is true: you can store anonymous types for which ...
但是第一部分:
因为您不必使用 Tuple.Create 指定类型
并不总是正确的.考虑以下场景:
is not always true. Consider the following scenario:
interface IAnimal
{
}
class Dog : IAnimal
{
}
以下不会编译:
Tuple<IAnimal> myWeirdTuple;
myWeirdTuple = Tuple.Create(new Dog());
您必须在 Create 方法中指定类型参数,如下所示:
You will have to specify the type parameter in the Create method like this:
myWeirdTuple = Tuple.Create<IAnimal>(new Dog());
这与调用 new Tuple(new Dog())
IMO 一样冗长
which is as verbose as calling new Tuple<IAnimal>(new Dog())
IMO
这篇关于Tuple.Create() 与新元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!