Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么StackTrace.GetFrames不直接返回引用?_C# - Fatal编程技术网

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

C# 为什么StackTrace.GetFrames不直接返回引用?,c#,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 StackFram

以下是
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;
}
公共虚拟堆栈帧GetFrame(int索引)
{
if((frames!=null)和&(index=0))
返回帧[index+m_imethodoskip];
返回null;
}
公共虚拟堆栈帧[]GetFrames()
{
如果(帧==null | | m|帧
为什么
GetFrames
不直接返回
frames

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

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

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


因为帧是不可变的,所以您不能更改它。因为它是只读的,所以不需要复制它。

我想您已经回答了自己的问题-StackFrame是不可变的类,而数组是可变的,所以返回数组引用将允许用户修改引用的对象。注释本身是否已经回答了这个问题?数组包含堆栈行在
GetFrames
中跳过此字段,这就是为什么不能返回完整数组,而只能返回一个subset@TimSchmelter添加了您的样品。谢谢。