How do you cast an object to a Tuple?

徘徊边缘 提交于 2021-02-07 11:18:21

问题


I create my Tuple and add it to a combo box:

comboBox1.Items.Add(new Tuple<string, string>(service, method));

Now I wish to cast the item as a Tuple, but this does not work:

Tuple<string, string> selectedTuple = 
                   Tuple<string, string>(comboBox1.SelectedItem);

How can I accomplish this?


回答1:


Don't forget the () when you cast:

Tuple<string, string> selectedTuple = 
                  (Tuple<string, string>)comboBox1.SelectedItem;



回答2:


Your syntax is wrong. It should be:

Tuple<string, string> selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;

Alternatively:

var selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;



回答3:


As of C# 7 you can cast very simply:

var persons = new List<object>{ ("FirstName", "LastName") };
var person = ((string firstName, string lastName)) persons[0];

// The variable person is of tuple type (string, string)

Note that both parenthesis are necessary. The first (from inside out) are there because of the tuple type and the second because of an explicit conversion.



来源:https://stackoverflow.com/questions/14605520/how-do-you-cast-an-object-to-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!