无法将我的类的实例添加到列表<my class>

Max*_*nko 1 powershell powershell-5.0

我有一个Powershell脚本声明一个类,然后尝试将此类的实例添加到列表中:

Add-Type -TypeDefinition @"
using System.Text.RegularExpressions;
public class BuildWarning
{
    public string Solution { get; private set; }
    public string Project { get; private set; }
    public string WarningMessage { get; private set; }
    public string WarningCode { get; private set; }
    public string Key { get; private set; }
    public bool IsNew { get; set; }
    private static readonly Regex warningMessageKeyRegex = new Regex(@"^(?<before>.*)\([0-9,]+\)(?<after>: warning .*)$");
    public BuildWarning(string solution, string project, string warningMessage, string warningCode)
    {
        Solution = solution;
        Project = project;
        WarningMessage = warningMessage;
        WarningCode = warningCode;
        var match = warningMessageKeyRegex.Match(WarningMessage);
        Key = Solution + "|" + Project + "|" + match.Groups["before"].Value + match.Groups["after"].Value;
    }
}
"@

[System.Collections.Generic.List``1[BuildWarning]] $warnings = New-Object "System.Collections.Generic.List``1[BuildWarning]"

[BuildWarning] $newWarning = New-Object BuildWarning("", "", "", "")

$warnings += $newWarning
Run Code Online (Sandbox Code Playgroud)

在最后一行,我收到一个错误:

Cannot convert the "System.Object[]" value of type "System.Object[]" to type
"BuildWarning".
At C:\development\temp\BuildWarningReportGenerator.ps1:93 char:17
+                 $warnings += $newWarning
+                 ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : ConvertToFinalInvalidCastException

我无法弄清楚问题是什么.类型检查显示两者的类型$warnings并且$newWarning是正确的.如何解决这个错误?

jya*_*yao 5

这样怎么样?

#do not use this way
#$warnings += $newWarning

#but use this instead
$warnings.Add($newWarning)
Run Code Online (Sandbox Code Playgroud)