Tuple.Create() vs new Tuple

后端 未结 5 1682
孤街浪徒
孤街浪徒 2021-02-02 06:18

Consider the following expressions:

new Tuple(1,2);

Tuple.Create(1,2);

Is there any difference between these two methods of Tup

5条回答
  •  礼貌的吻别
    2021-02-02 07:09

    Well, this questions is old... but nevertheless I think I may contribute constructively. From the accepted answer:

    I suppose one benefit is that, since you don't have to specify the type with Tuple.Create, you can store anonymous types for which you otherwise wouldn't be able to say what the type is

    The consequence is true: you can store anonymous types for which ...

    But the first part:

    since you don't have to specify the type with Tuple.Create

    is not always true. Consider the following scenario:

    interface IAnimal
    {
    }
    
    class Dog : IAnimal
    {
    }
    

    The following will not compile:

    Tuple myWeirdTuple;
    
    myWeirdTuple = Tuple.Create(new Dog());
    

    You will have to specify the type parameter in the Create method like this:

    myWeirdTuple = Tuple.Create(new Dog());
    

    which is as verbose as calling new Tuple(new Dog()) IMO

提交回复
热议问题