我想声明一个这样的类型:
type
TDynMatrix<T> = TArray<TArray<T>>;
Run Code Online (Sandbox Code Playgroud)
编译器拒绝这个:
[dcc32 Error] E2508 Type parameters not allowed on this type
我想知道这个问题是否与泛型的嵌套有关.但似乎不是:
type
TDynArray<T> = TArray<T>;//pointless type I know, but for the sake of the Q
Run Code Online (Sandbox Code Playgroud)
也导致相同的编译器错误.
编译器错误的文档让我知道在我阅读它之前可能比我知道的还要少:
此类型不允许使用E2508类型参数(Delphi)
使用类引用时,不能直接使用泛型类.您需要使用包装类才能使用泛型.
Run Code Online (Sandbox Code Playgroud)program E2508; {$APPTYPE CONSOLE} uses SysUtils; type TMyClass = class end; TMyClassClass<T> = class of TMyClass; begin Writeln('FAIL - E2508 type parameters not allowed on this type'); end.
任何人都可以解释为什么我不能以这种方式声明泛型类型?
您的代码无效,因为您无法将泛型类型重新声明为开放泛型类型。
我将其声明为:
type
TDynMatrix<T> = array of TArray<T>;
Run Code Online (Sandbox Code Playgroud)
这样,您仍然具有可能需要的兼容性:一维元素到TArray<T>.
那么你可以写
var
matrix: TDynMatrix<Integer>;
values: TArray<Integer>;
....
SetLength(matrix, 2, 2);
values := matrix[0];
values := Copy(matrix[1]);
Run Code Online (Sandbox Code Playgroud)
ETC。
| 归档时间: |
|
| 查看次数: |
412 次 |
| 最近记录: |