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

Ale*_*dru 9 .net c# combobox tuples

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

comboBox1.Items.Add(new Tuple<string, string>(service, method));
Run Code Online (Sandbox Code Playgroud)

现在我希望将项目作为元组投射,但这不起作用:

Tuple<string, string> selectedTuple = 
                   Tuple<string, string>(comboBox1.SelectedItem);
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点?

Céd*_*non 17

不要忘记()你投的时间:

Tuple<string, string> selectedTuple = 
                  (Tuple<string, string>)comboBox1.SelectedItem;
Run Code Online (Sandbox Code Playgroud)

  • @TYY 如果由于某种意外原因它不是元组,它将隐藏错误。如果您知道某些东西属于 T 类型,则使用强制转换,如果您知道某些东西可能属于 T 类型,但它是有效的行为,即使它没有用作和空测试 (2认同)

Dom*_*eon 10

从 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)
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,这也是可能的,但在这种情况下,您需要使用“person.Item1”和“person.Item2”而不是“person.firstName”和“person.lastName” (2认同)

Dan*_*ley 6

您的语法错误。它应该是:

Tuple<string, string> selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;
Run Code Online (Sandbox Code Playgroud)

或者:

var selectedTuple = (Tuple<string, string>)comboBox1.SelectedItem;
Run Code Online (Sandbox Code Playgroud)