Cast lost when ternary with mismatched branch types is hoisted to `object` local

未关闭
#3,736 3 条评论 1 个 reaction 已指派 1 人 在 GitHub 查看

维护者通常 1 天内回复

@siegfriedpammer 已经在做这个了。

开始于 2026年8月27日。

评估

这个 Issue 还没有评估数据。

描述

Bug Feedback Needed

When a ?:'s two branches have different stack types and ILSpy can't find a common type tighter than object, it hoists the conditional into an if/else with an object obj local — but drops the explicit cast that was present in the source. The dropped cast can re-bind to a different overload on recompile.

Repro
using System.Collections.Generic;
using System.Linq;

public class Repro
{
    public IEnumerator<byte> Bug(byte[] data, bool reversed)
        => (reversed ? ((IEnumerable<byte>)data).Reverse() : (IEnumerable<byte>)data).GetEnumerator();
}
ilspycmd 10.0.1.8346 output
public IEnumerator<byte> Bug(byte[] data, bool reversed)
{
    object obj;
    if (!reversed)
    {
        obj = data;
    }
    else
    {
        obj = data.Reverse();  // (IEnumerable<byte>) cast lost
    }
    return ((IEnumerable<byte>)obj).GetEnumerator();
}

When a project-local void Reverse(this byte[]) (or similar shadowing extension) is in scope, data.Reverse() re-binds to it on recompile → CS0029 ("Cannot implicitly convert type 'void' to 'object'"). Even without a shadow, the decompile is semantically lossy.

dotPeek emits the inline ternary form with both casts preserved.

Related

#1501, #1614, #3322, #3464, #793 are all in the same family (ILSpy dropping a needed cast); none is exactly this ?:→if/else hoist variant.

主要语言
C#
星标
27.1k
派生
3.8k
平均合并
1 天 23 小时
30 天内合并 PR
44

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

icsharpcode/ILSpy 的其他 Issue

查看 icsharpcode/ILSpy 的全部 Issue

相似的 Issue

更多 C# Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。