小编rob*_*lle的帖子

将Nullable Enum设置为$ null - 这是否真的导致PSInvalidCastException?

在PowerShell中将Nullable Enum设置为$ null会导致System.Management.Automation.PSInvalidCastException异常.这是出乎意料的(至少对我来说).对此有合理的解释吗?下面是一个示例,显示如何设置Nullable Int32是否成功,但设置Nullable Enum会导致异常:

Add-Type @"
public enum ColorEnum
{
    Red = 1,
    Blue = 2,
    Green = 3,
}

public class Thing
{
    public ColorEnum? NullableColor = ColorEnum.Blue;
    public System.Int32? NullableInt = 123;
}
"@

$test = New-Object Thing

# Setting the Nullable Int32 to $null works, as expected.
$test.NullableInt = $null

# Setting the Nullable Enum to $null causes exception.
$test.NullableColor = $null
Run Code Online (Sandbox Code Playgroud)

异常消息显示为:

异常设置"NullableColor":"由于枚举值无效,无法将null转换为类型"ColorEnum".请指定以下枚举值之一并重试.可能的枚举值为"红色,蓝色,绿色".

我希望能够使用Nullable Enum而不是默认值为0的Enum的原因是因为我想要使用的Enum表示可以为空的数据库列,当没有设置有效值时,该列应该为null .我无法更改数据库模型,所以不幸的是,感觉解决方案可能是使用Int32而不是Enum.

还有其他人经历过这个吗?这可能是一个错误吗?

$ PsVersionTable:

Name                           Value                                                                                                                                                                                            
----                           ----- …
Run Code Online (Sandbox Code Playgroud)

.net powershell enums nullable powershell-3.0

7
推荐指数
1
解决办法
480
查看次数

标签 统计

.net ×1

enums ×1

nullable ×1

powershell ×1

powershell-3.0 ×1