2013-07-03 26 views
1

我有一个这样的通用接口:集通用接口的

public interface IHardwareProperty<T>{ 
bool Read(); 
bool Write(); 
} 

这是一个抽象基类“穿过”:

public abstract class HardwareProperty<T>:IHardwareProperty<T>{ 
//Paritally implements IHardwareProperty (NOT SHOWN), and passes Read and Write through 
//as abstract members. 
    public abstract bool Read(); 
    public abstract bool Write(); 
} 

,并在使用几个不同的继承类完成泛型参数

CompletePropertyA:IHardwareProperty<int> 
{ 
    //Implements Read() & Write() here 
} 

CompletePropertyBL:IHardwareProperty<bool> 
{ 
    //Implements Read() & Write() here 
} 

我想存储一堆不同的完成属性类型在同一个集合中。 有没有办法做到这一点,而不诉诸于收集object

+2

我看到这里完成你想要的是将非通用接口作为什么的唯一方式通用的基础,例如'公共接口IHardwareProperty :IHardwareProperty'然后存储基础之一:'List propertyList' ... –

+0

为什么你的接口是通用的呢?你永远不会使用'T' ... –

+0

谢谢,我发布了几分钟后才发现这一点。我想输入这个问题帮助我解决了这个问题。我改变了它,所以IHardwareProperty有一个'对象GetValue()'方法。这并不是很好,因为当我通过这个价值获得价值时,我仍然必须抛弃它,但它完成了工作。 – Benjamin

回答

5

您需要使用所有这些类型都支持的类型。您可以通过使您IHardwareProperty<T>接口不通用做到这一点:

public interface IHardwareProperty 
{ 
    bool Read(); 
    bool Write(); 
} 

由于没有在你的界面使用T的方法,这是完全适当的。如果在接口方法或属性中使用泛型类型,那么使接口泛型化的唯一原因是。

注意,如果这是必需的或期望的实现细节的基础类还是可以通用:

public abstract class HardwareProperty<T> : IHardwareProperty 
{ 
    //... 
0

不幸的是,因为每个具有不同类型参数的泛型都被视为完全不同的类型。

typeof(List<int>) != typeof(List<long>)