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

时间:2017-06-06 09:06:08

标签: 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没有方法或属性来修改自己。

1 个答案:

答案 0 :(得分:3)

  

为什么GetFrames不返回frames

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

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

  

为什么GetFrame会返回引用而不是复制?

因为框架是不可变的,所以无法更改它。没有必要复制它,因为它是只读的。