2017-07-04 85 views
1

下面的C#代碼片段嵌入在powershell(.ps1)文件中,並生成了System.Management.Automation.RuntimeException。刪除「字符串」,異常消失。試圖使用大寫「字符串」,並試圖添加命名空間「System.String」和其他各種方法,但仍然得到例外。這讓我瘋狂,請幫我理解爲什麼會發生這種情況。如何在.ps1文件中創建C#字符串對象

$code = @" 
public static class foo 
{ 
    public static bool check() 
    { 
    string s; 
    return false; 
    } 
} 

代碼是這樣調用的;

try 
{ 
    Add-Type -TypeDefinition $code -Language CSharp 
} 
catch{} // ignore TYPE_ALREADY_EXISTS exception 
$res = [foo]::check(); 

這裏是異常的細節;

Exception: System.Management.Automation.RuntimeException: unable to find type [foo]. 
TargetObject: foo 
CategoryInfo: InvalidOperation (foo:Typename) [], RuntimeException 
FullyQualifiedErrorId: TypeNotFound 
InvocationInfo: System.Management.Automation.InvocationInfo 
+5

請發佈足夠的代碼,以便我們至少可以重現問題。定義字符串值'$ code'顯然不會自己編譯你的類 –

回答

0
$code = @" 
public static class foo { 
    public static bool check() { 
    string s; 
    return false; 
    } 
} 
"@ 

Add-Type -TypeDefinition $code -Language CSharp 

產生

Warning as Error: The variable 's' is declared but never used

它不會讓你聲明未使用的變量。

+0

有一個簡單的解決方案,但我們不知道OP在做什麼 –

+0

是的,我知道。這就是我爲什麼離開它的原因。這太長了評論。 – Nkosi

+0

您的回答幫助我瞭解如何在PowerShell環境中更好地開發C#代碼。謝謝。 – Lars