通用接口集合



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

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>接口非通用来实现这一点:

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(),它将返回bool或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>,这很难看,老实说,我不太确定这到底在做什么。

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);

最新更新