gpt4 book ai didi

.net - 内联 .Net 方法时,属性会发生什么情况?

转载 作者:行者123 更新时间:2023-12-02 15:43:27 26 4
gpt4 key购买 nike

我在一个类中有一些代码,它正在爬行堆栈跟踪以查找其调用堆栈中方法的特定属性。

我注意到我的一个测试从自动构建开始失败,而该测试总是从我的机器上通过。当我深入研究时,发现只要附加了调试器,相关代码就可以在 Debug模式或 Release模式下正常工作,但在没有调试器的 Release模式下会失败。

据我所知,我正在寻找的方法正在被内联,当发生这种情况时,该方法上的属性就会丢失。

是这样吗?此时属性是否会丢失?

这是一个重现我的问题的小应用程序:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;


namespace InliningAndAttributes
{

public class SomeClass
{

[Description("Foo")]
public void SomeMethodThatWillGetInlined()
{
SomeMethodThatWontGetInlined();
}

protected virtual void SomeMethodThatWontGetInlined()
{
var caller = FindDescribedCaller();
Console.WriteLine("Could I find description attribute? {0}", caller != null);
}

private MethodBase FindDescribedCaller()
{
var callStack = new StackTrace();
int frameIndex = 0;
while (frameIndex++ <= callStack.FrameCount)
{
Console.WriteLine("Getting frame" + frameIndex);
var currentFrame = callStack.GetFrame(frameIndex);
if (currentFrame == null)
{
continue;
}
var method = currentFrame.GetMethod();
Console.WriteLine(method.Name);
if (Attribute.IsDefined(method, typeof(DescriptionAttribute)))
{
return method;
}
}
return null;
}
}

class Program
{
static void Main(string[] args)
{
var someClass = new SomeClass();
someClass.SomeMethodThatWillGetInlined();

Console.ReadLine();
}
}
}

当我在 .Net 4.5 下运行此应用程序时,使用发布版本且未附加调试器,我得到以下输出:

Getting frame1
SomeMethodThatWontGetInlined
Getting frame2
Main
Getting frame3
Getting frame4
Could I find description attribute? False

最佳答案

用户代码无法检测内联。如果可以的话,这将是一个损坏的编译器优化。优化是无法检测到的(当然,除非它们利用了未定义或未指定的行为)。

问题不在于属性丢失。错误是您的代码依赖于运行时 StackTrace ,它确实具有未指定的内容。这是一个提供尽力而为数据的调试类。内联删除堆栈帧。

您可能不应该依赖于您的方法的调用者。 (不仅因为它不起作用,还因为它非常脆弱并且不能 self 记录)。寻找不同的解决方案。通过传递附加参数让调用者识别自己。

关于.net - 内联 .Net 方法时,属性会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24203813/

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