【问题标题】:Reflection with Powershell使用 Powershell 进行反射
【发布时间】:2009-04-02 16:16:39
【问题描述】:

我有一组 .NET 程序集(都在同一个目录下),其中一些包含实现抽象类的类。我想要一个 Powershell 脚本来查找所有实现我的抽象类的类,并在每个类上执行一个方法。

有人知道怎么做吗?

谢谢!

【问题讨论】:

    标签: reflection powershell assemblies


    【解决方案1】:

    这是您可能想尝试的一个小功能..(我还没有测试它,因为我没有任何标准可以轻松测试它..)

    可以像这样在命令行中提供路径(一个或多个完整路径或以逗号分隔的相对路径)来使用它

    CheckForAbstractClassInheritance -Abstract System.Object -Assembly c:\assemblies\assemblytotest.dll, assemblytotest2.dll
    

    或来自管道

    'c:\assemblies\assemblytotest.dll','assemblytotest2.dll' | CheckForAbstractClassInheritance -Abstract System.Object
    

    或使用 Get-Childitem (dir) 中的 fileinfo 对象

    dir c:\assemblies *.dll | CheckForAbstractClassInheritance -Abstract System.Object
    

    根据需要进行调整..

    function CheckForAbstractClassInheritance()
    {
        param ([string]$AbstractClassName, [string[]]$AssemblyPath = $null)
        BEGIN
        {
            if ($AssemblyPath -ne $null)
            {
                $AssemblyPath | Load-AssemblyForReflection
            }
        }
        PROCESS
        {
            if ($_ -ne $null)
            {
                if ($_ -is [FileInfo])
                {
                    $path = $_.fullname
                }
                else
                {
                    $path = (resolve-path $_).path
                }
                $types = ([system.reflection.assembly]::ReflectionOnlyLoadFrom($path)).GetTypes()
                foreach ($type in $types)
                {
                    if ($type.IsSubClassOf($AbstractClassName))
                    {
                        #If the type is a subclass of the requested type, 
                        #write it to the pipeline
                        $type
                    }
                }
    
            }
        }
    }
    

    【讨论】:

    • 这里唯一的问题是您不能实例化类或执行从仅用于反射而加载的程序集中的方法。
    【解决方案2】:

    与使用 c# 的方法相同,但使用 PowerShell 语法。
    看看Assembly.GetTypesType.IsSubclassOf

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      相关资源
      最近更新 更多