我正在尝试创建一个用户通过从UI 上List<T>
选择数据类型来指定数据类型的位置。ComboBox
我已经设法创建了一个包含 的对象CustomEntity
,List<T>
但是一旦我退出Button1_Click
事件处理程序,CustomEntity
就会超出范围。是否可以创建类级别变量?我尝试过,但不得不将其注释掉,因为它导致了错误。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CustomClassWithGenericList
{
public partial class Form1 : Form
{
//The following error is created: Cannot implicitly convert type
//CustomClassWithGenericList.CustomEntity<decimal> to
//CustomClassWithGenericList.CustomEntity<object>
//private CustomEntity<object> input1;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (cb1.SelectedItem.ToString().ToUpper() == "DECIMAL")
{
input1 = new CustomEntity<decimal>();
string[] temp = textBox1.Text.Split(',');
foreach (string s in temp)
{
decimal number;
if (decimal.TryParse(s, out number))
{
input1.inputValue.Add(number);
}
else
{
MessageBox.Show("Error occured.");
}
}
}
else if(cb1.SelectedItem.ToString().ToUpper() == "INT")
{
}
else if(cb1.SelectedItem.ToString().ToUpper() == "TIMESPAN")
{
}
}
}
public class CustomEntity<T>
{
public List<T> inputValue;
public CustomEntity()
{
inputValue = new List<T>();
}
}
}