C# 如何将对象强制转换为元组?

C# 如何将对象强制转换为元组?,c#,.net,combobox,tuples,C#,.net,Combobox,Tuples,我创建元组并将其添加到组合框: comboBox1.Items.Add(new Tuple<string, string>(service, method)); comboBox1.Items.Add(新元组(服务、方法)); 现在我希望将该项转换为元组,但这不起作用: Tuple<string, string> selectedTuple = Tuple<string, string>(comboBox1.Sele

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

comboBox1.Items.Add(new Tuple<string, string>(service, method));
comboBox1.Items.Add(新元组(服务、方法));
现在我希望将该项转换为元组,但这不起作用:

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

我如何才能做到这一点?

您的语法错误。应该是:

Tuple<string, string> selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;
Tuple selectedTuple=(Tuple)组合框1.SelectedItem;
或者:

var selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;
var selectedTuple=(Tuple)comboBox1.SelectedItem;
在施放时不要忘记
()

Tuple<string, string> selectedTuple = 
                  (Tuple<string, string>)comboBox1.SelectedItem;
Tuple selectedTuple=
(元组)组合框1.SelectedItem;
从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)
var persons=新列表{(“FirstName”、“LastName”)};
var person=((string firstName,string lastName))persons[0];
//变量person是元组类型(string,string)

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

谢谢!我在所有的括号里都迷路了。一旦计时器过期,我会将你的帖子标记为最佳答案!或元组selectedTuple=(comboBox1.SelectedItem作为元组)@TYY,如果由于某些意外原因它不是一个元组,它将隐藏一个错误。如果您知道某个对象是T类型的,那么使用强制转换;如果您知道某个对象可能是T类型的,但是它是有效的,即使它不是用作和nulltest@Rune根据他是如何使用tuple对象的,检查null与抛出异常是有意义的。即使我知道塞德里克的答案绝对正确,也只是给他另一个选项。@TYY是的,这正是我所说的,在他知道应该始终是指定的元组类型的情况下,强制转换是合适的选项(因为如果强制转换失败,根据定义,这是一种例外情况)如果该对象在法律上可以是其他对象,则是合适的选项