Skip to main content
 首页 » 编程设计

c#之通用接口(interface)集合

2024年02月01日28del

我有一个像这样的通用接口(interface):

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 集合的情况下做到这一点?

请您参考如下方法:

您需要使用所有这些都支持的类型。你可以通过制作你的 IHardwareProperty<T> 来做到这一点接口(interface)非通用:

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

因为您的接口(interface)中没有任何方法使用 T ,这是完全合适的。使接口(interface)通用的唯一原因是,如果您在接口(interface)方法或属性中使用通用类型。

请注意,如果实现细节需要或需要,您的基类仍然可以是通用的:

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