在加载类型定义之前使用.NET类型进行强制转换

时间:2015-12-16 22:10:57

标签: c# .net powershell types casting

我只是想知道在包含定义的程序集加载之前是否可以使用声明类型。

我有一个powershell v5类,我想整齐地声明。 见下文:

class MySQL
{

[MySql.Data.MySqlClient.MySqlConnection]
$connection

[MySql.Data.MySqlClient.MySqlCommand]
$_command


static MySQL()
{   
    if(([appdomain]::currentdomain.getassemblies() | Where {$_ -match "MySql.Data"}) -eq $null)
    {
        Write-Verbose "MySQL assembly has not been loaded yet. Try to load....";

        try
        {
            [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
        }
        catch
        {
            if([MySQL]::getConnectorFromWeb())
            {
                [void][System.Reflection.Assembly]::Load("MysqlL.Data, Version=$script:version, Culture=neutral, PublicKeyToken=c5687fc88969c44d")

            }
            else
            {
                throw "MySQL connector import failed!"
            }
        }
    }
    else
    {
        return
    }

#different other methods....
}

现在无法解析此脚本,因为在脚本开始时属性的类型不存在。例如。第一次调用静态构造函数导入程序集时,[MySql.Data.MySqlClient.MySqlConnection]将可用。

我不确定是否有可能这样做。至少在实际解释的PowerShell中,即使脚本只是“读取”,它也不会创建我的新类型“MySql”,因为它无法解析属性。

知道我怎么能摆脱这个“TypeNotFound”异常,但仍然使用类似强制类型的静态类型定义? (PowerShell实际上是动态的,不一定需要显式类型引用)

增加: 现在我添加了一个这样的方法:

   [MySql.Data.MySqlClient.MySQLConnection]getConnection()
   {
       return $this.connection
   }

当然这也无法解析,因为类型[MySql.Data.MySqlClient.MySQLConnection]尚未知晓。我认为在C#中没问题,因为你不会动态加载程序集,而是使用“using”语句声明所有必要的环境。但这在PowerShell中是不可能的:(

0 个答案:

没有答案