c# - 有没有办法将组合框中的选定项目转换为代码?
问题描述
我想将用户在组合框中选择的项目转换为可执行程序集,这样我就可以直接从类中输出,而无需编写单独的 if 语句。我确实对此进行了搜索,但找不到对我有用的答案。我得到的 lblOne.Text = cboComboBox.SelectedItem.aString 的错误消息是:“object”不包含“aString”的定义,并且没有可访问的扩展方法“aString”接受“object”类型的第一个参数(您是否缺少 using 指令或程序集引用?)。抱歉,如果我发布了太多代码,这是我第二次在这里发布。这是我尝试对其进行编码:
// in public partial class Form1: Form : A one = new A("One", "Cool");
public class A
{
// Instance Variables
string Name;
string Info;
// Constructor Declaration of Class
public A(string Name, string Info)
{
this.Name = Name;
this.Info = Info;
}
// method 1
public string getName()
{
return Name;
}
// method 2
public string getInfo()
{
return Info;
}
//output to label
public string aString()
{
return ("Name: " + this.getName() + "\n" +
"Info: " + this.getInfo() + "\n");
}
private void btnStats_Click(object sender, EventArgs e)
{
lblOne.Text = cboComboBox.SelectedItem.aString();
//doesn't actually work
//what I want it to be in code: lblOne.Text = one.aString();
}
解决方案
组合框/列表框等的 SelectedItem 属性将所选项目作为Object返回。
在使用该属性之前,您需要将其转换为您的类类型
((YourClassName)comboBox.SelectedItem).YourProperty
或者
(comboBox.SelectedItem as YourClassName).YourProperty
推荐阅读
- pdf - 在多页 PDF 中逐页阅读 PDF
- tidy - 错误:nlsModel 类的对象没有整洁的方法
- node.js - 在有效模式的情况下快速验证给出 404
- tensorflow - 带有图像的 pbtxt/pb 文件的推理测试
- java - 如何将地图定义为常量对象,而不是每次调用时都会创建的方法
- c++ - 如何在 C++ 上的游戏中添加加载游戏功能
- java - 如何从命令提示符运行驻留在另一个 jar 中的 jar
- php - 提供的 paytm 校验和无效
- java - 读取 Excel 表,将列数据存储在数组中,遍历数组中的每个值并将其与门户网站上的数据进行比较
- javascript - 有没有办法在另一个页面和它自己的 URL 中显示一个 html 页面?