简体   繁体   English

您将如何进行这种设计?

[英]How would you approach this design?

I have ControlA which accepts an IInterfaceB which has a property of type List<unknownType> 我有ControlA接受IInterfaceB ,该IInterfaceB具有类型为List<unknownType>的属性

In an event of ControlA i need to add a new instance of unknownType to the List in IInterfaceB ... 在事件ControlA我需要一个新的实例添加unknownType在列表IInterfaceB ...

unknownType needs specific properties so i immediately thought it could be an interface, but quickly realised interfaces cannot be instantiated... unknownType需要特定的属性,因此我立即认为它可以是接口,但是无法实例化快速实现的接口...

How would you design this system? 您将如何设计该系统?

EDIT the current inheritance chain looks like this: 编辑当前的继承链如下所示:

topLevelClass -> baseObject -> IBaseObject (which is implemented in topLevelClass)

so if i added a new class to the chain it would need to do the inheriting and implementing which would be impossible (afaik) 因此,如果我在链中添加了一个新类,则将需要进行继承和实现,这是不可能的(afaik)

If I'm interpreting this correctly, you could add a constraint on unknownType to be of some interface that contains the properties you need: 如果我正确地解释了这一点,则可以在unknownType上添加一个约束,使其成为包含所需属性的某些接口:

class ControlA
{
    void Frob<T>(IInterfaceB<T> something) where T : IHasSomeProperties, new()
    {
        something.ListOfT.Add(new T() { SomeProperty = 5 });
        something.ListOfT.Add(new T() { SomeProperty = 14 });
    }
}

对类型的限制会起作用吗?

List<T> where T : IInterface

Your specification isn't specific enough to answer well, but try putting constraints on T. 您的规范不够具体,无法很好地回答,但请尝试在T上设置约束。

public interface IInterfaceB<T>
    where T : new()
{
    List<T> Whatever { get; }
}

This allows you to do this: 这使您可以执行以下操作:

T iDoNotCare = new T();

Why does List have to be an unknowntype? 为什么列表必须是未知类型? Why can't it be a real class, the has the real properties you need with a constructor for you to instantiate? 为什么它不能是一个真正的类,它具有您需要的实例化构造函数才能实例化? If you need to extend that class, you can then inherit from it. 如果需要扩展该类,则可以从该类继承。 Based on the information you're providing, if all you need is a few properties in the class that goes into this List, then a good old class should do the trick. 根据您提供的信息,如果只需要该列表中的类中的几个属性,那么一个好的老类应该可以解决问题。

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

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