Use of Supports() function with generic interface type

前端 未结 2 1799
南方客
南方客 2020-12-10 05:22

I just tried my first use of generics in Delphi 2009 and am perplexed on how to use a generic type as the input to the Supports function used to see if an object implements

相关标签:
2条回答
  • 2020-12-10 06:06

    There is no guarantee that T has a GUID associated with it, and there is no means in the language to write a constraint on the type parameter to make that guarantee.

    The interface name is converted into a GUID by the compiler looking up the name in the symbol table, getting the compiler's data structure representing the interface, and checking the corresponding field for the GUID. But generics are not like C++ templates; they need to be compiled and type-checked and known to work for any valid type parameter, and that means constraining the type parameter in its declaration.

    You can get the GUID using RTTI (first checking that T does indeed represent an interface) with something like GetTypeData(TypeInfo(T))^.Guid and pass the GUID to Supports that way.

    0 讨论(0)
  • 2020-12-10 06:10

    Why are you even bothering?

    To use this TFunctions.GetInterface you need:

    • an interface
    • an object reference

    If you have those, then you can just call Supports() directly:

      intf := TFunctions.GetInterface<IMyInterface>(myObject);
    

    is exactly equivalent to:

      Supports(IMyInterface, myObject, intf);
    

    Using generics here is a waste of time and effort and really begs the question "Why Do It?".

    It is just making things harder to read (as is so often the case with generics) and is more cumbersome to use.

    Supports() returns a convenient boolean to indicate success/failure, which you have to test for separately using your wrapper:

      intf := TFunctions.GetInterface<IMyInterface>(myObject);
      if Assigned(intf) then
        // ...
    

    versus:

      if Supports(IMyInterface, myObject, intf) then
        // We can use intf
    

    When creating wrappers around functionality it is generally the case that the result is an improvement in readabilty or usability.

    imho this fails on both counts and you should just stick with the Supports() function itself.

    0 讨论(0)
提交回复
热议问题