开发者

Accessing members of a generic type

Lets say I have 2 class types TEmployee (with properties A,B) and TDept (with properties C,D). Then I make a class descended from TList like so :

TMyCcontainer<T>=class(TList<T>)

So I can create instances of TMyCcontainer and fill with TEmployee or TDept. In my TMyCcontainer class is there anyway to access properties A,B of TEmployee, or properties C,D of TDept?

Of course the type is generic so it would appear not. And this is the problem I always have with generics - maybe I am mis-using them. I recently learnt abaout constraints, and thought I had found out what I had been miss开发者_运维问答ing....

So I created 2 interfaces say IEmployee and IDept, made my 2 orig class es to be interfaceobjects, and put in my contraint on my Tlist ie

TMyCcontainer<T:IEmployee,IDept>=class(TList<T>)

Of course I was quickly disappointed as this is saying you must implement BOTH of these interfaces in any type I put in my generic TList (TMyContainer), whereas I just want ONE in any particular instance, then ther other in another instance. I would have to implement both IEmployee and IDept in my TDept class which is not what I want obv.

Is there any good way to access members of a Type within a generic container? Or should I not be using generics to do this type of thing. Ty


All generic constraints you put on a class have to be fulfilled by the generic type. Looks like what you're really looking for is two different generic types: TMyContainer<TDept> and TMyContainer<TEmployee>. Then you'll have access to all the properties of those types, individually.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜