如何制作泛型类和列表 [英] How to make a generic class, and list

查看:100
本文介绍了如何制作泛型类和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含60多个表的数据库,我在其中创建了一个对应的类,该类封装了表中每列的属性。我希望这些类在UI和UI之间移动数据。数据库。我想创建一组通用代码来创建实例,创建列表,并使用数据添加类对象。以下是2个完全手动的代码集,为2个大小的用户和项目表执行此操作:

I have a database with over 60 tables where I created a corresponding class that encapsulates a property for each column in the table. I want the classes to move data between UI & the database. I want to create a generic set of code to create an instance, create a list, and add class objects with the data. The following is 2 completely manual code sets that do this for 2 sized down "user" and "project" tables:

string myName = "NNNNN";
string myPassword = "PPPPP";
DBUser dbUser = new DBUser();
List<dbuser> list1 = new List<dbuser>();
list1.Add(new DBUser { Name = myName, Password = myPassword });

string myDescLong = "LLLLL";
string myDescShort = "SSSSSS";
DBProject dbProject = new DBProject();
List<dbproject> list2 = new List<dbproject>();
list2.Add(new DBProject { Desc_long = myDescLong, Descr_short = myDescShort }); 


class DBProject
{
   private string desc_long;
   public string Desc_long
   {get { return this.desc_long; } set { this.desc_long = value; }}

   private string descr_short;
   public string Descr_short
   {get { return this.descr_short; } set { this.descr_short = value; } }
}

class DBUser
{
   private string password;
   public string Password
   {get { return this.password; } set { this.password = value; }
}
   private string name;
   public string Name
   {get { return this.name; } set { this.name = value; } }
}



现在回答我的问题。我如何概括这一点,所以我不会有58个额外的实例,列表,添加到列表代码?也许这是不可能的?



有点像发送DbUser类名,它可以动态创建下面的代码吗?


Now to my question. How do I generalize this so I don;t have 58 additional sets of the instance, list, add to list code? Maybe it isn't possible?

Something like send the "DbUser" classname and it can dynamically create the code below?

type DBGeneric = DBUser;
type Data = "All property data";

DBGeneric dbGeneric = new DBGeneric();
List<dbgeneric> listGeneric = new List<dbgeneric>();
listGeneric.Add(new DBGeneric { Data });

推荐答案

您可以使用此代码作为如何创建动态通用数据类型的示例:

You can use this code as an example of how to create a dynamic generic data type:
public object CreateGeneric(Type generic, Type innerType, params object[] args)
{
    Type specificType = generic.MakeGenericType(new Type[] { innerType });
    return Activator.CreateInstance(specificType, args);
}



然后用想要的数据类型调用方法。

在这种情况下,我用int创建了一个列表。 />


Then call the method with the wanted data type.
In this case I created a list with int.

List<int> list = (List<int>)CreateGeneric(typeof(List<>), typeof(int));
list.Add(2);
list.Add(3);





如果你不要太依赖于你自己的类,你可以查看类DataTable。

与DataAdapter类一起,很容易从数据库中提取数据并在数据网格中显示。

这是更通用的方法,可能会为您节省一些工作。

DataAdapter类 [ ^ ]


这篇关于如何制作泛型类和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆