繁体   English   中英

通用列表 <T> 类级变量

[英]Generic List<T> class level variable

我正在尝试创建一个List<T> ,其中用户通过在UI上的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>();
        }
    }
}

注释掉的行使用类型T,它不是定义的类型。 并不是说你需要在decleration点指定泛型的类型参数列表,而不是其他任何地方。

如果希望泛型能够保存任何对象,则应该简单地将类型“object”作为类型参数传递给它。

如果它只能有几种不同的类型,那么每种类型创建一个成员变量可能是一个首选选项,具体取决于您以后计划如何使用它。

那里有很多技术可以使用。 首先,您可以创建Object动态类型变量,只需将其任意投射即可。

此外,您可以将数据存储在内存中的某些状态(如某些会话或应用程序状态,或缓存,类似的东西),在这种情况下,只需从此源获取它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM