这是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 returnframes
?
嗯,frames
变量是内部存储。因此,作为返回值的接收者,您可以通过设置数组的索引来更改内部存储变量。为了防止这种情况,它将不可变对象(immutable对象)复制到一个新数组(其大小比数组的堆栈大小更好)。
此外,正如注释所述:我们必须返回数组的子集。因此不会返回整个数组。可以找到一个示例 here :DiagnosticTrace
中的所有方法都被过滤掉。
Why does
GetFrame
return the reference instead of copy?
因为框架是不可变的,所以您无法更改它。由于它是只读的,因此无需复制它。
关于c# - 为什么 StackTrace.GetFrames 不直接返回引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44385798/