有谁知道为什么指示的行有错误?
根据类型兼容性页面,这似乎是一个编译器错误。通配符是 T1,TStringWildcard2 是 T2。
也根据这个
如果表达式的值在 T1 的范围内并且至少满足以下条件之一,则可以将 T2 类型的表达式分配给 T1 类型的变量:T1 是 IUnknown 或 IDispatch 接口类型,并且 T2 是 Variant 或OleVariant。(如果 T1 是 IUnknown,则变体的类型代码必须是 varEmpty、varUnknown 或 varDispatch,如果 T1 是 IDispatch,则必须是 varEmpty 或 varDispatch。)
如果 T1 是 IUnknown 并且 T2 是 OleVariant,则可以将 T2 类型的表达式分配给 T1 类型的变量 - 因此第二个错误行也应该编译。
ACollection2 := ACollection1; // 理论上应该编译,但没有。由于 LWildcard := TStringWildcard2.Create (编译,因为 LWildcard 被声明为 Wildcard 接口的变量,并且 TStringWildcard2 实现了 Wildcard 接口)。
As such, therefore, ACollection2 (TDictionary<string, Wildcard> ) := ACollection1; (TDictionary<string, TStringWildcard2>) should compile right?
program TestCollections;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Generics.Collections;
type
Wildcard = interface
['{941128E5-D87C-4E3E-98D8-CF45EE6FEC09}']
procedure Clear;
end;
Wildcard<T> = interface(Wildcard)
function getMatch: T;
end;
TParent = class(TInterfacedObject)
end;
TStringWildcard1 = class(TParent, Wildcard<string>)
function getMatch: string;
procedure Clear;
end;
TStringWildcard2 = class(TParent, Wildcard, Wildcard<string>)
function getMatch: string;
procedure Clear;
end;
{ TStringWildcard1 }
procedure TStringWildcard1.Clear;
begin
end;
function TStringWildcard1.getMatch: string;
begin
Result := 'String match 1';
end;
{ TStringWildcard2 }
procedure TStringWildcard2.Clear;
begin
end;
function TStringWildcard2.getMatch: string;
begin
Result := 'String match 2';
end;
var
LWildcard: Wildcard;
ACollection1: TDictionary<string, TStringWildcard2>;
ACollection2, ACollection3: TDictionary<string, Wildcard>;
ACollection4: TDictionary<string, IUnknown>;
begin
LWildcard := TStringWildCard2.Create; // <-- TStringWildcard2 compatible with Wildcard
// Since TStringWildcard2 is compatible with Wildcard, therefore,
// ACollection1 should be compatible with ACollection2
ACollection1 := TDictionary<string, TStringWildcard2>.Create;
ACollection2 := ACollection1;
ACollection4 := TDictionary<string, OleVariant>.Create;
end.