问题
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