Generics: What's a “CONSTRUCTOR constraint”?

后端 未结 2 1825
轮回少年
轮回少年 2021-01-04 23:27

I made a custom TObjectList descendant designed to hold subclasses of a base object class. It looks something like this:

interface
   TMyDataList

        
相关标签:
2条回答
  • 2021-01-04 23:59

    Just a quick update to an old question..

    You don't need the constructor constraint and can also do this on object's with parameters by using RTTI like this (using RTTI or System.RTTI with XE2)

    constructor TMyDataList<T>.Create;
    var
      ctx: TRttiContext;
    begin
       inherited Create(true);
       self.Add(
         ctx.
         GetType(TClass(T)).
         GetMethod('create').
         Invoke(TClass(T),[]).AsType<T>
       );
    end;
    

    If you have parameters, just add them like this

    constructor TMyDataList<T>.Create;
    var
      ctx: TRttiContext;
    begin
       inherited Create(true);
       self.Add(
         ctx.
         GetType(TClass(T)).
         GetMethod('create').
         Invoke(TClass(T),[TValue.From('Test'),TValue.From(42)]).AsType<T>
       );
    end;
    
    0 讨论(0)
  • 2021-01-05 00:01

    You're trying to create an instance of T via T.Create. This doesn't work because the compiler doesn't know that your generic type has a parameterless constructor (remember: this is no requirement). To rectify this, you've got to create a constructor constraint, which looks like this:

    <T: constructor>
    

    or, in your specific case:

    <T: TBaseDatafile, constructor>
    
    0 讨论(0)
提交回复
热议问题