简体   繁体   English

访问泛型类型的成员

[英]Accessing members of a generic type

Lets say I have 2 class types TEmployee (with properties A,B) and TDept (with properties C,D). 假设我有2个类类型TEmployee(具有属性A,B)和TDept(具有属性C,D)。 Then I make a class descended from TList like so : 然后我像TList一样从TList那里下课:

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

So I can create instances of TMyCcontainer and fill with TEmployee or TDept. 所以我可以创建TMyCcontainer的实例并填充TEmployee或TDept。 In my TMyCcontainer class is there anyway to access properties A,B of TEmployee, or properties C,D of TDept? 在我的TMyCcontainer类中,无论如何都要访问TEmployee的属性A,B或TDept的属性C,D?

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 missing.... 我最近学会了很多约束,并且认为我找到了我所遗漏的东西......

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 所以我创建了2个接口说IEmployee和IDept,使我的2个原型类es成为interfaceobjects,并在我的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. 当然我很快就失望了,因为这就是说你必须在我放入我的通用TList(TMyContainer)的任何类型中实现这些接口的两个,而我只想在任何特定实例中使用ONE,然后在另一个实例中使用其他类型。 I would have to implement both IEmployee and IDept in my TDept class which is not what I want obv. 我必须在我的TDept类中实现IEmployee和IDept,这不是我想要的obv。

Is there any good way to access members of a Type within a generic container? 有没有什么好方法可以访问通用容器中的Type成员? 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> . 看起来你真正想要的是两种不同的泛型类型: TMyContainer<TDept>TMyContainer<TEmployee> Then you'll have access to all the properties of those types, individually. 然后,您将可以单独访问这些类型的所有属性。

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

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