请考虑以下PowerShell代码段:
$csharpString = @"
using System;
public sealed class MyClass
{
public MyClass() { }
public override string ToString() {
return "This is my class. There are many others " +
"like it, but this one is mine.";
}
}
"@
Add-Type -TypeDefinition $csharpString;
$myObject = New-Object MyClass
Write-Host $myObject.ToString();
Run Code Online (Sandbox Code Playgroud)
如果我在同一个AppDomain中多次运行它(例如在powershell.exe或powershell_ise.exe中运行两次脚本),我会收到以下错误:
Add-Type : Cannot add type. The type name 'MyClass' already exists.
At line:13 char:1
+ Add-Type -TypeDefinition $csharpString;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (MyClass:String) [Add-Type],
Exception
+ FullyQualifiedErrorId …Run Code Online (Sandbox Code Playgroud) 我有一个C#程序,如果存在名称空间,类或方法,我如何在运行时检查?另外,如何使用字符串形式的名称实例化一个类?
伪代码:
string @namespace = "MyNameSpace";
string @class = "MyClass";
string method= "MyMEthod";
var y = IsNamespaceExists(namespace);
var x = IsClassExists(@class)? new @class : null; //Check if exists, instantiate if so.
var z = x.IsMethodExists(method);
Run Code Online (Sandbox Code Playgroud)