如何将对象转换为元组

本文关键字:元组 转换 对象 | 更新日期: 2023-09-27 17:56:52

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

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

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

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

我怎样才能做到这一点?

如何将对象转换为元组

不要忘了投法时的()

Tuple<string, string> selectedTuple = 
                  (Tuple<string, string>)comboBox1.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)

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

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

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

或者:

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