将运行时类型传递给泛型方法

时间:2015-10-22 16:00:07

标签: c# generics

我试图重构某些代码,但我不确定我是否会采用正确的方法。

下面是一个简化的开关,我根据传递给通用函数的2个参数创建了一个可观察的集合。第一个参数始终是一个可观察的集合,第二个参数是存储在observable集合中的对象的类型:

switch (csvDataType)
{
  case CsvDataTypeEnum.Supplier:
    dataCollection = ConverterService.ConvertCsvDataToCollection
    <SupplierCollection, Supplier>(csvData);
    break;
  case CsvDataTypeEnum.Currency:
    dataCollection = ConverterService.ConvertCsvDataToCollection
    <CurrencyCollection, Currency>(csvData);
    break;
  case CsvDataTypeEnum.Custom:
    dataCollection = ConverterService.ConvertCsvDataToCollection
    <CustomDataObjectCollection, CustomDataObject>(csvData);
    break;
}

基于以上所述,我希望将代码重构为与此类似的东西:

ObjectInfo objectInfo = new ObjectInfo(csvDataType);

Type objectType = objectInfo.ObjectType;
Type collectionType = objectInfo.CollectionType;

dataCollection = ConverterService.ConvertCsvDataToCollection
<collectionType, objectType>(csvData);

我的ConvertCsvDataToCollection泛型函数定义如下:

public static U ConvertCsvDataToCollection<U, T>(string csvData) 
where U : ObservableCollection<T>
{
....
}

然后我使用var隐式类型:

var dataCollection = Activator.CreateInstance(collectionType);

并且它创建了所需类型的正确可观察集合,但是我不能通过这样调用它来获取我希望的类型collectionType和objectType类型的泛型函数:

dataCollection = ConverterService.ConvertCsvDataToCollection
<collectionType, objectType>(csvData);

但是我收到以下错误:

the 'type or namespace name 'collectionType' could not be found. Are you missing a directive or assembly reference'

对于collectionType和objectType参数我传递给我的泛型函数。

有没有办法实现这个目标?我知道这可能是以前曾经问过的,但我需要澄清,因为我到目前为止所读到的其他类似问题仍然没有解决我的问题,或者我完全错过了他们的观点。对不起,如果是这样的话!

感谢。

0 个答案:

没有答案
相关问题