我正在開發一個PoSh項目,該項目生成CSharp代碼,然後Add-Type
將其存儲到內存中。如何獲取PowerShell添加類型使用添加類型
新類型使用通過Add-Type加載的磁盤DLL中的現有類型。
一切都很好,直到我真的嘗試調用新類型的方法。下面是我在做什麼的例子:運行上面的腳本
$PWD = "."
rm -Force $PWD\TestClassOne*
$code = "
namespace TEST{
public class TestClassOne
{
public int DoNothing()
{
return 1;
}
}
}"
$code | Out-File tcone.cs
Add-Type -OutputAssembly $PWD\TestClassOne.dll -OutputType Library -Path $PWD\tcone.cs
Add-Type -Path $PWD\TestClassOne.dll
$a = New-Object TEST.TestClassOne
"Using TestClassOne"
$a.DoNothing()
"Compiling TestClassTwo"
Add-Type -Language CSharpVersion3 -TypeDefinition "
namespace TEST{
public class TestClassTwo
{
public int CallTestClassOne()
{
var a = new TEST.TestClassOne();
return a.DoNothing();
}
}
}" -ReferencedAssemblies $PWD\TestClassOne.dll
"OK"
$b = New-Object TEST.TestClassTwo
"Using TestClassTwo"
$b.CallTestClassOne()
給出的最後一行出現以下錯誤:
異常調用「CallTestClassOne」和「0」的說法(S): 「無法加載文件或程序集'TestClassOne,...' 或它的某個依賴項,系統找不到指定的文件。「 在AddTypeTest.ps1:39字符:20 + $ b.CallTestClassOne < < < <() + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException
我在做什麼錯?
謝謝你。我認爲Add-Type沒有獲得它所需的API可用性測試。 – 2010-04-19 12:08:24
它在這些位置查找,因爲這是應用程序的(PowerShell的)基本目錄 - [appdomain] :: CurrentDomain.BaseDirectory。除非你在PowerShell.exe的配置文件(不推薦)中添加專用探測路徑,否則CLR加載器將在那裏或在該位置的某些子分區中查找。 – 2010-04-19 17:20:49
@凱蒂,你說得對。然而,問題是爲什麼PowerShell試圖加載程序集,即使程序集已經加載。奇怪的是:| – stej 2010-04-19 18:18:16