如何在 .ps1 文件中创建 C# 字符串对象
How to create C# string object inside .ps1 file
下面的 C# 代码片段嵌入到 powershell (.ps1) 文件中并生成了一个 System.Management.Automation.RuntimeException。删除 "string s" 异常消失。尝试使用大写 "String" 并尝试添加命名空间 "System.String" 和各种其他方法,但仍然出现异常。这让我抓狂,请帮助我理解为什么会这样。
$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
$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
它不允许您声明未使用的变量。
下面的 C# 代码片段嵌入到 powershell (.ps1) 文件中并生成了一个 System.Management.Automation.RuntimeException。删除 "string s" 异常消失。尝试使用大写 "String" 并尝试添加命名空间 "System.String" 和各种其他方法,但仍然出现异常。这让我抓狂,请帮助我理解为什么会这样。
$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
$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
它不允许您声明未使用的变量。