相关疑难解决方法(0)

如果尚未添加具有Add-Type -TypeDefinition的类,如何有条件地添加类?

请考虑以下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)

powershell add-type

43
推荐指数
4
解决办法
1万
查看次数

C# - 如何检查C#中是否存在名称空间,类或方法?

我有一个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)

c# methods namespaces class

37
推荐指数
2
解决办法
4万
查看次数

标签 统计

add-type ×1

c# ×1

class ×1

methods ×1

namespaces ×1

powershell ×1