泛型问题
泛型定义:
- Delphi(Pascal) code
unit uGlobal;interfacetype Tiif<T> = class public class function iif<T>(bFlag: Boolean; aValue: T; bValue: T): T; end;implementation{ Tiif<T> }class function Tiif<T>.iif<T>(bFlag: Boolean; aValue, bValue: T): T;begin if bFlag then Result := aValue else Result := bValue; end;end.调用的时候,提示[DCC Error] uPlayer.pas(32): E2532 Couldn't infer generic type argument from different argument types for method 'iif'
调用代码:
Index := Tiif<Integer>.iif(Index < 7, Index + 1, 0);
如果把Index + 1改成一个常数就没有问题。
这个是什么原因呢?
[解决办法]
泛型过程, 需要有数据类型
- Delphi(Pascal) code
//如果只是过程需要泛型, 可以这么写Tiif = class public class function iif<T>(bFlag: Boolean; aValue: T; bValue: T): T; end;{ Tiif<T> }class function Tiif.iif<T>(bFlag: Boolean; aValue, bValue: T): T;begin if bFlag then Result := aValue else Result := bValue;end;var index : Integer;begin index := StrToInt(edt1.Text); Index := Tiif.iif<Integer>(Index < 7, index, 0); Caption := IntToStr(index);