代码检查:可能的 'System.InvalidCastException'
此检查报告了在运行时可能因 InvalidCastException 而失败的显式类型转换。
示例
using System;
static void Handle(object value)
{
if (value is Action<string>)
{
var action = (Action<int>)value;
}
}
类型检查证明 value 是 Action<string> ,因此将其转换为 Action<int> 是不安全的。
如何修复它
没有针对此检查的专用快速修复。 通常的修复方法是转换为实际检查的类型,或使用模式匹配。
using System;
static void Handle(object value)
{
if (value is Action<string> action)
{
action("text");
}
}
2026年 5月 8日