gpt4 book ai didi

c# - 如何将 DebuggerHidden 与迭代器 block 方法结合使用?

转载 作者:太空狗 更新时间:2023-10-29 23:52:18 25 4
gpt4 key购买 nike

DebuggerHidden 非常方便标记辅助方法,确保未处理的异常在方便的地方停止调试器:

enter image description here

不幸的是,这似乎不适用于迭代器 block :

enter image description here

(如果是,调试器会将 in 显示为第二个示例中的当前语句)。

虽然这显然是 Visual Studio 的局限性(我有 submitted a report ),但有没有什么方法可以解决这个问题,同时仍然使用迭代器 block ?

我猜这是因为编译器生成的实现迭代器的代码没有用 [DebuggerHidden] 标记。也许有某种方法可以说服编译器这样做?

最佳答案

也许不是您希望的答案,但作为一种解决方法,它可以获得一些分数...不确定您是否已经想到了这一点。

有一个帮助程序类来解包您的迭代器,然后使用扩展方法使包装器在您的迭代器上发挥作用。我处理异常并重新抛出。在 VS2010 中,我不得不奇怪地取消选中调试选项“仅启用我的代码”以获得接近 OP 要求的行为。保持选中该选项仍然会使您进入实际的迭代器,但 ik 看起来像一行太远了。

这使得这个答案更像是一个实验,以证明和支持该场景需要更好的编译器支持。

扩展方法辅助类:

public static class HiddenHelper
{
public static HiddenEnumerator<T> Hide<T>(this IEnumerable<T> enu )
{
return HiddenEnumerator<T>.Enumerable(enu);
}
}

包装器:

public class HiddenEnumerator<T> : IEnumerable<T>, IEnumerator<T>
{
IEnumerator<T> _actual;
private HiddenEnumerator(IEnumerable<T> enu)
{
_actual = enu.GetEnumerator();
}

public static HiddenEnumerator<T> Enumerable(IEnumerable<T> enu )
{
return new HiddenEnumerator<T>(enu);
}

public T Current
{
[DebuggerHidden]
get
{
T someThing = default(T);
try
{
someThing = _actual.Current;
}
catch
{
throw new Exception();
}
return someThing;
}
}

public IEnumerator<T> GetEnumerator()
{
return this;
}

IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}

public void Dispose()
{
_actual.Dispose();
}

object IEnumerator.Current
{
get { return _actual.Current; }
}

[DebuggerHidden]
public bool MoveNext()
{
bool move = false;
try
{
move = _actual.MoveNext();
}
catch
{
throw new IndexOutOfRangeException();
}
return move;
}

public void Reset()
{
_actual.Reset();
}
}

用法:

        public IEnumerable<int> Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
if (result>Int16.MaxValue) throw new Exception();
result = result * number;
yield return result;
}
}

public void UseIt()
{
foreach(var i in Power(Int32.MaxValue-1,5).Hide())
{
Debug.WriteLine(i);
}
}

关于c# - 如何将 DebuggerHidden 与迭代器 block 方法结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11056478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com