Get derived class type from a base's class static method

前端 未结 8 979
走了就别回头了
走了就别回头了 2020-12-01 14:44

i would like to get the type of the derived class from a static method of its base class.

How can this be accomplished?

Thanks!

class BaseCla         


        
8条回答
  •  天命终不由人
    2020-12-01 14:58

    I think the following will work for this case (and several similar ones elsewhere on SO). Perf won't be too good, but if this is infrequent, that won't be a problem.

    Create a stacktrace and parse it looking for a derived class. In the general case this wouldn't be too reliable or might not even work, but in specific cases, like that in the OP, I believe this will work fine. In Powershell:

    $strace = (new-object diagnostics.stacktrace).tostring()
    #
    $frames = $strace -split "   at "
    $typesFromFrames = $frames | select -skip 1| # skip blank line at the beginning
       % { ($_ -split "\(",2)[0]} |                 # Get rid of parameters string
       % {$_.substring(0,$_.lastindexof("."))} |    # Get rid of method name
       $ {$_ -as [type]}
    #
    # In powershell a lot of the frames on the stack have private classes
    #  So $typesFromFrames.count is quite a bit smaller than $frames.count
    #  For the OP, I don't think this will be a problem because:
    #   1. PS isn't being used
    #   2. The derived class in the OP isn't private 
    #        (if it is then tweaks will be needed)
    #
    $derivedOnStack = $typesFromFrames | ? { $_.issubclassof( [BaseClass])}
    

    Hopefully there will just be one element in $derivedOnStack, but it will depend on the particulars of the application. Some experimentation will be required.

提交回复
热议问题