我怎样才能让一个类型安全气囊的项目,所有的实现一个通用接口?

人气:1,034 发布:2022-09-10 标签: .net generics

问题描述

需要有一个类型安全袋的物品,所有实现一个通用接口。

的愿望就是做这样的事情:

  VAR StringItem的=新的iItem<字符串>();
VAR numberItem =新的iItem<诠释>();
VAR项目=新的名单,其中,的iItem< T>>(); //当然,T不能做到我想要的

items.Add(StringItem的);
items.Add(numberItem);
 

是这样的:

 接口的iItem
{
   对象值{获得;组; }
}

//更新:2009-03-19下午3点08分MST
//添加了以下接口清楚我的问题

接口的iItem< T> :的iItem
{
   新款T值{获得;组; }
}
 

然后,我可以:

  VAR项目=新的名单,其中,的iItem>();
 

不过,我失去的类型安全在我的包里。于是,我想到了词典

  VAR字典=新字典<类型,列表和LT;的iItem< T>>>(); // T是错了

dict.Add(typeof运算(字符串),新的名单,其中,的iItem<字符串>>); //这看起来确实不错
 

解决方案

我不认为你可以逃避一个事实,即的iItem< INT> 的iItem<字符串> 是不同的;通常的做法是基本接口:

 接口的iItem {
   对象值{获取;}
}
接口的iItem< T> :{的iItem
   新款T值{获得;}
}
 

这样的话,你对的iItem code,但实际情况(通常实施的iItem< T> 一些 T )的stll内部强类型。

Need to have a type-safe bag of items that all implement a generic interface.

The desire is to do something like:

var stringItem = new IItem<string>();
var numberItem = new IItem<int>();
var items = new List<IItem<T>>(); //T of course doesn't accomplish what I want

items.Add(stringItem);
items.Add(numberItem);

Something like:

interface IItem
{
   object Value { get; set; }
}

//Update: 2009-03-19 03:08 PM MST
//Added the following interface for clarity of my question

interface IItem<T> : IItem
{
   new T Value { get; set; }
}

Then, I could:

var items = new List<IItem>();

But, I lose type safety in my bag. So, I thought of Dictionary:

var dict = new Dictionary<Type, List<IItem<T>>>(); //T is wrong again

dict.Add(typeof(string), new List<IItem<string>>); //that sure looks nice

解决方案

I don't think you can escape the fact that IItem<int> and IItem<string> are different; the usual approach is a base-interface:

interface IItem {
   object Value {get;}
}
interface IItem<T> : IItem {
   new T Value {get;}
}

That way, you code against IItem, but the actual instances (that typically implement IItem<T> for some T) are stll strongly-typed internally.

201