繁体   English   中英

通用接口的集合

[英]Collection of Generic Interfaces

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

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 s的集合吗?

您需要使用所有这些类型都支持的类型。 您可以通过使IHardwareProperty<T>接口为非通用接口来实现:

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

由于界面中的任何方法都不使用T ,因此这是完全合适的。 使接口通用的唯一原因是,如果您在接口方法或属性中使用通用类型。

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

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

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

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

为后代张贴此内容:我的问题几乎与此相同,但是稍作调整后,我的界面确实使用了通用类型。

我有多个实现通用接口的类。 目标是拥有多个<Int/Bool/DateTime>Property类,每个类包含一个字符串( _value )和一个getValue()函数,这些函数在调用时会将字符串_value转换为不同的类型,具体取决于接口的实现。

public interface IProperty<T>
{
    string _value { get; set; }
    T getValue();
};

public class BooleanProperty : IProperty<bool>
{
    public string _value { get; set; }
    public bool getValue()
    {
        // Business logic for "yes" => true
        return false;
    }
}

public class DateTimeProperty : IProperty<DateTime>
{
    public string _value { get; set; }
    public DateTime getValue()
    {
        // Business logic for "Jan 1 1900" => a DateTime object
        return DateTime.Now;
    }
}

然后,我希望能够将多个这些对象添加到单个容器中,然后在每个容器上调用getValue() ,它将返回布尔值,DateTime或其他取决于类型的对象。

我以为我可以做到以下几点:

List<IProperty> _myProperties = new List<IProperty>();

但这会产生错误:

Using the generic type 'IProperty<T>' requires 1 type arguments

但是我还不知道该列表的类型,所以我尝试添加<object>

List<IProperty<object>> _myProperties = new List<IProperty<object>>();

然后编译。 然后,我可以将项目添加到集合中,但是我需要将它们IProperty<object>IProperty<object> ,这很难看,而且老实说,我不确定这到底是做什么的。

BooleanProperty boolProp = new BooleanProperty();
// boolProp.getValue() => returns a bool
DateTimeProperty dateTimeProp = new DateTimeProperty();
// dateTimeProp.getValue(); => returns a DateTime
_myProperties.Add((IProperty<object>)boolProp);
_myProperties.Add((IProperty<object>)dateTimeProp);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM