Use of Supports() function with generic interface type

前端 未结 2 1815
南方客
南方客 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: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(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(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.

提交回复
热议问题