开发者

Factory method for generics in VB.NET

I want to create a factory for generic classes in VB.NET and I am running into issues.

What I have are two interfaces: IPersistentObject and IPManagerBase(Of T as IPersistentObject)

The logic is that for each type of peristent object I have a corresponding manager class handling query logic.

Now I have a base class like this:

public class PManagerBase(Of T as IPersistentObject) Implements IPManagerBase(of T)

So, now in the real world I have a persistent type "PUse开发者_StackOverflow中文版r" and a corresponding manager declared like this:

public class PUserManager implements PManagerBase(Of PUser)

I have about 100 of those persistent objects and corresponding manager classes.

Now I want to have a factory, which I would invoke like this (removing the details):

MyFactory.CreateManager<PUserManager>()

I am creating my Factory like this

public class MyFactory
    public shared function CreateManager(Of T as {PManagerBase(Of IPersistentObject), New}) as T
         return new T()
    end function
end class

Looks great.

Now I want to invoke it:

Dim myManager = MyFactory.CreateManager<PUserManager>()

What happens? I get a compile error: "PUserManager does not implement/inherit PManagerBase(Of IPersistentObject)". I get the message in German so this is a free tranlation.

What would I need to change to make this running? It works if I declare my factory like this:

public class MyFactory
    public shared function CreateManager(Of T as {PManagerBase(Of PUser), New}) as T
         return new T()
    end function
end class

But then the benefit is gone, since it works only for Managers of the PUser object.

A better solution is

public class MyFactory
    public shared function CreateManager(Of T as {PManagerBase(Of U), New}, U as IPersistentObject) as T
         return new T()
    end function
end class

This works, but I have to call my factory method like this now:

Dim myManager = MyFactory.CreateManager<PUserManager, PUser>()

I don't like this since this is redundant and I don't need U at all in the function. In it's declaration PUserManager is tied to PUser.

Is there a better way? Why is PUserManager not inheriting from PManagerBase(Of IPersistentObject)?


This is a problem with generics, if you are using VS 2010 you may want to take a look at covariance and contravariance and modify your IPManagerBase definition accordingly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜