你如何将一个物体投射到一个元组?

时间:2013-01-30 13:44:47

标签: c# .net combobox tuples

我创建了我的元组并将其添加到组合框中:

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

现在我希望将项目强制转换为元组,但这不起作用:

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

我该如何做到这一点?

3 个答案:

答案 0 :(得分:14)

投射时不要忘记()

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

答案 1 :(得分:4)

你的语法错了。它应该是:

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

可替换地:

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

答案 2 :(得分:2)

从C#7开始,您可以轻松转换:

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

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

请注意,两个括号都是必需的。第一个(从里到外)是因为元组类型,第二个是由于显式转换。

相关问题