如何在C#中编写泛型方法 [英] How to write Generic Method in C#

查看:124
本文介绍了如何在C#中编写泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据库返回的记录集

该记录集用于5种不同的交易,我在这里知道交易类型.

因此我需要从此记录集中创建5个不同的对象,因为5个事务中的每个事务都是不同的类型.

然后,我调用每个事务的处理方法,并将接受对象传递给事务.
=======================

这种方法有两个问题.

1.从数据库返回的记录集中,我想创建一个具有键值"对的集合,其中键"是数据库列"的名称,值"是数据库列"的值,并将其存储在字典"中,在字典"中的键是交易类型",值"是我的集合,我不知道该如何实现?

2.我想编写一个通用方法,将在步骤1中创建的Dictionary和事务类型传递给该方法,该方法应向我返回特定于Transaction类型的对象.

我是Generics的新手,所以有人可以帮我吗.

预先表示感谢.

I have a record set returned from the DB

this recordset is used for 5 different transactions, I know the transaction Type here.

so I need to create 5 different Objects from this record set as each of 5 transactions are of different type.

Then I call the process method of each transaction and pass the resceptive object to the transation.
=========================

I have two problmes in this approach.

1. from the recordset returned by DB, I want to create a collection with Key Value pair, where Key is DB Column name and value is DB Column value and store it in a Dictionary, in Dictionary key is Transaction Type and value is my collection, I dont know how can I achieve that?

2. I want to write a generic method, to which I will pass the Dictionary created in step 1 and transaction type and that method should return me the object specific to the Transaction type.

I am very new to Generics, so can someone please help me in doing that.

Thanks in advance.

推荐答案

请参阅有关

创建新词典:

var lookup = new Dictionary< string,>();

将您的键和值添加到字典中

lookup.Add(数据库键值,数据库集合);

Create a new dictionary:

var lookup = new Dictionary<string,>();

add your key and value to the dictionary

lookup.Add(DB Key Value, DB collection);

var mainDictionary = new Dictionary<Type, Dictionary<string, , object>>();



获得正确的收藏:



get the right collection:

public Dictionary<string, object> GetCollection<T>(Dictionary<Type, Dictionary<string, object>> mainDictionary)
{
    return mainDictionary.Where(x => x.Key == typeof(T)).Select(x => x.Value).SingleOrDefault();
}





注意,这是Psuedo代码,因此指出它的任何奖励都不会编译;-)





NB this is Psuedo code, so no prizes for pointing out it won''t compile ;-)


这篇关于如何在C#中编写泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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