c# - 为什么 StackTrace.GetFrames 不直接返回引用?

标签 c#

这是StackTrace的源代码。

public virtual StackFrame GetFrame(int index)
{
    if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
        return frames[index+m_iMethodsToSkip];

    return null;
}

public virtual StackFrame [] GetFrames()
{
    if (frames == null || m_iNumOfFrames <= 0)
        return null;

    // We have to return a subset of the array. Unfortunately this
    // means we have to allocate a new array and copy over.
    StackFrame [] array = new StackFrame[m_iNumOfFrames];
    Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
    return array;
}

为什么GetFrames不只返回frames?如果它不希望调用者修改帧,为什么 GetFrame 返回引用而不是副本?

顺便说一下, StackFrame没有方法或属性来修改自身。

最佳答案

Why doesn't GetFrames just return frames?

嗯,frames 变量是内部存储。因此,作为返回值的接收者,您可以通过设置数组的索引来更改内部存储变量。为了防止这种情况,它将不可变对象(immutable对象)复制到一个新数组(其大小比数组的堆栈大小更好)。

此外,正如注释所述:我们必须返回数组的子集。因此不会返回整个数组。可以找到一个示例 here :DiagnosticTrace 中的所有方法都被过滤掉。

Why does GetFrame return the reference instead of copy?

因为框架是不可变的,所以您无法更改它。由于它是只读的,因此无需复制它。

关于c# - 为什么 StackTrace.GetFrames 不直接返回引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44385798/

相关文章:

c# - .NET从本地报告读取ReportParameter

C#克隆一个交叉引用列表

C# Process StandardInput 和 StandardOutput 与 FFmpeg 卡住

c# - 如何访问对象的某些(私有(private))属性?

c# - Razor 中的共享辅助函数

c# - Silverlight 中附加和非附加依赖属性之间的区别

c# - 使用 Func 作为 LinqToEntities 的参数

c# - 规范中是否实现了自动属性?

c# - 单声道语音识别

c# - Ninject.MVC 构造函数注入(inject),其中注入(inject)对象的构造函数采用参数