PowerShell 5和类-无法转换“ X”类型“ X”的值键入“ X” [英] PowerShell 5 and classes - Cannot convert the "X" value of type "X" to type "X"

查看:114
本文介绍了PowerShell 5和类-无法转换“ X”类型“ X”的值键入“ X”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PowerShell的类,这是将相关数据分组在一起的非常方便的方法,并且在处理行为方面非常繁琐。简化的情况是:一个定义类的PS脚本和另一个使用该类的脚本。

I'm trying to use PowerShell's classes that is very handy way of grouping related data together and facing quite tedious to deal with behavior. The simplified scenario: one PS script that defines class and another script that uses that class.


Common.ps1

Common.ps1



class X
{
    [string] $A
} 




Script1.ps1

Script1.ps1



. $PSScriptRoot\Common.ps1

[X] $v = New-Object X

一切都很好-您可以任意次数运行 Script1.ps1 次,没有问题-直到对<$>进行任何更改为止c $ c> Common.ps1 。您将遇到以下错误。

Everything is good - you can run Script1.ps1 arbitrary amount of times with no issues - until you make any change in Common.ps1. You will face the following error.


Cannot convert the "X" value of type "X" to type "X".
At D:\temp\PSIssue\Script1.ps1:3 char:1
+ [X] $v = New-Object X
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

可以想象PS文件中的任何更改(即使您刚刚添加了空格)都将强制其重新编译,因此键入 X 与以前的 X 有所不同-临时容器组装已更改(在.NET中很容易重现的同一问题-类型相同,只要完全合格程序集名称)。 Script1.ps1 中的更改使事情再次正常运行。

Conceivably any change (even if you just added whitespace) in PS file forces its recompilation, so that type X becomes different than X it used to be - temporary container assembly has been changed (the very same issue easily reproducible in .NET - types are identical as long as "Fully Qualified Assembly Names" are the same). Change in Script1.ps1 makes things function normally again.

有什么方法可以克服此类问题?

Is there any way to overcome such kind of issues?

推荐答案

我能够复制并解决您的问题。这类似于您在范围内定义一个类,然后尝试在同一范围内定义另一个类。类定义保留在PowerShell会话中。在Script1.ps1中,您需要修改代码以不显式声明要键入的变量。只需使用以下操作不使用强类型,然后让PowerShell确定类型并动态分配它即可:

I was able to replicate and resolve your issue. It is similar to if you define a class in a scope and you try to define another class in the same scope. The class definition is retained in PowerShell session. In Script1.ps1 you need to modify the code to not explicitly declare the variable to type. Just use as below to not use Strong Typing and let PowerShell determine the type and assign it dynamically:

. $PSScriptRoot\Common.ps1

$v = New-Object X

现在您应该可以在Common.ps1中随意更改X类的定义,而无需关闭并重新加载。

Now you should be able to change the definition of class X in Common.ps1 as many times as you want without needing to close and reload.

上面的示例使用弱输入,您可以在此处阅读有关此内容和其他详细信息的更多信息:变量类型和强类型输入

The example above uses "Weak typing" You can read more about this and other details here: Variable Types and Strongly Typing

这篇关于PowerShell 5和类-无法转换“ X”类型“ X”的值键入“ X”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆