我有一个 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
在最后一行我收到错误:
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
的类型都是正确的。如何修复这个错误?
最佳答案
这样怎么样?
#do not use this way
#$warnings += $newWarning
#but use this instead
$warnings.Add($newWarning)
关于powershell - 无法将我的类的实例添加到列表<我的类>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123320/