开发者

How to implement polymorphic interface with generic custom collection

ok - so what I want to accomplish is this: Build a poly interface making use of a generic collection that accepts one of three custom types (constrained through an interface).

The problem lies around when I write an implementation for

public virtual CustCollection<CustType1&g开发者_运维百科t; GetEntities()
{
    return new CustCollection<CustType1>();
}

And then attempt to override it at the next level of derevation. It's not even an option for me to override this implementation.

The other possibility is making use of an interface, but then I need the interface to accept generic, not specify type...which I cannot seem to get working

i.e. what I need is:

interface IAccess<T>
{
    CustCollection<T> GetEntities();
}

but this is not an option it seems...

Any suggestions?


Did I get you right? :)

public interface IUnknown { }

public class SoAndSo : IUnknown { }

public class CustomCollection<IUnknown>
{
}

public class Ancestor<T> where T : IUnknown
{
    public virtual CustomCollection<T> GetEntities()
    {
        return null;
    }
}

public class Descender : Ancestor<SoAndSo>
{
    public override CustomCollection<SoAndSo> GetEntities()
    {
        return base.GetEntities();
    }
}


I ended up creating an interface (IAccess as shown above) and placed the constraint of type on that interface...then made use of that interface on all classes interacting with the types in question.

so (sorry this is high level, I can't write my actual implementation out)

interface IAccess<T> where T : ITypeInterface
{
    CustCollection<T> GetEntities(Filter filter);
}

I attempted what was suggested, but I have a chain of 3 classes inheriting and had issues with the top most parent using the suggested model.

I left the constraint on the custom collection:

 public class CustCollection<T> : IEnumerable<T> where T : ITypeInterface
    {}

This only really worked for me because I realized I really did not need to share functionality with the parent classes (so basically did not end up enforcing true polymorphism...only in the sense of common object interaction, core functionality is entirely seperate).

To avoid shadowing, I declare new

  public new CustCollection<Type> GetEntities(Filter filter)
    {
        return new CustCollection<Type>();
    }

I hope this is helpful to some...though I did not achieve exactly what I set out to do in the beginning, I found this to be a suitable workaround for my situation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜