基本上,我想要一个类能够实现相同通用接口的两个不同版本。做泛型接口名称映射?
考虑以下代码
type
// a generic interface
ITest<T> = interface
['{6901FE04-8FCC-4181-9E92-85B73264B5DA}']
function Val: T;
end;
// a class that purports to implement two different types of that interface
TTest<T1, T2> = class(TInterfacedObject, ITest<T1>, ITest<T2>)
protected
fV1: T1;
fV2: T2;
public
constructor Create(aV1: T1; aV2: T2);
function Val: T1; // Val() for ITest<T1>
function T2Val: T2; // Val() for ITest<T2>
function ITest<T2>.Val = T2Val; // mapping
end;
constructor TTest<T1, T2>.Create(aV1: T1; aV2: T2);
begin
inherited Create;
fV1 := aV1;
fV2 := aV2;
end;
function TTest<T1, T2>.T2Val: T2;
begin
result := fV2;
end;
function TTest<T1, T2>.Val: T1;
begin
result := fV1;
end;
/////////////
procedure Test;
var
t : TTest<integer, string>;
begin
t := TTest<integer, string>.Create(39, 'Blah');
ShowMessage((t as ITest<string>).Val); // this works as expected
ShowMessage(IntToStr((t as ITest<integer>).Val)); // this gets AV
end;
第一ShowMessage显示“胡说”为我所期望的,但第二次崩溃。它崩溃的原因是因为调用调用T2Val()而不是Val(),正如我所预料的那样。显然,冲突解决映射为两种类型的接口映射方法,而不仅仅是针对ITest:T2。
所以,这是我的问题。
这是一个错误?我的意思是,Embarcadero打算如何支持它,并简单地实施它是错误的?还是他们从来没有任何意图让程序员做这样的事情呢? (老实说,我有点惊讶,我的测试程序甚至编译过)
如果这是一个错误,有没有人有任何想法,接口?
呵呵。很高兴知道。谢谢。你只是巴里信息的金矿。感谢您花时间。 – TrespassersW 2009-11-12 05:39:26
D2010已经这个哈希了,巴里? – 2009-11-12 13:31:25
不幸的是,它不。我真的应该看看它。 – 2009-11-12 15:06:45