【问题标题】:Change Generated C# Class Name更改生成的 C# 类名称
【发布时间】:2010-09-30 18:19:14
【问题描述】:

我正在使用ManagementClass.GetStronglyTypedClassCode 来获取对 CodeTypeDeclaration 实例的引用。我想更改生成的类名,但此方法不允许这样做(据我所知)。我试图更改 CodeTypeDeclaration.Name 属性,但这不会更改构造函数名称等,因此 C# 编译器在编译类时会返回错误。我可以对班级进行简单的搜索/替换,但这似乎不可靠。有没有办法可靠地更改由 CodeTypeDeclaration 实例表示的 C# 类的名称?

代码不多,但这里是相关的sn-p(我用的是PowerShell):

$WmiClassName = 'Win32_Process'
$ClassName = 'MyProcess'

$WmiClass = New-Object `
    System.Management.ManagementClass($WmiClassName)

$classCode = $WmiClass.GetStronglyTypedClassCode($true, $false)
$classCode.Name = $ClassName # This doesn't change constructor names

【问题讨论】:

    标签: c# powershell code-generation wmi codedom


    【解决方案1】:

    我认为您可以通过枚举Members 属性并更改CodeConstructor 类型成员的Name 属性来手动重命名构造函数

    【讨论】:

    • 对不起,我犯了一个错误。当我更改 CodeTypeDeclaration.Name 属性时,它确实会更改构造函数名称。没有改变的是构造函数中使用的类静态方法。例如,如果我将名称从“Service”更改为“Win32_Service”,则其中一个构造函数如下所示: public Win32_Service(string keyName) { this.InitializeObject(null, new System.Management.ManagementPath(Service.ConstructPath(keyName)) , 空值); } 其中 Service.ConstructPath 应该是 Win32_Service.ConstructPath。
    • 好吧,那就有点难解决了……您可能需要访问 CodeDom 对象中的所有节点来替换类型名称。我想不出更简单的方法...
    • 谢谢,我会调查的。只是希望有更简单的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多