gpt4 book ai didi

c# - 函数参数(params object [])有什么区别

转载 作者:行者123 更新时间:2023-11-30 17:04:23 24 4
gpt4 key购买 nike

我正在尝试理解复杂的库 (LinqToCodeDom),其中有很多 lambda 和委托(delegate)等等。两个相同的代码(在我看来)工作方式不同。在这两种情况下,我都尝试传递一个 TypeA 对象数组。

作品:

Func(new TypeA[] { new TypeA("value") });

不起作用:

TypeA [] v = new TypeA[] { new TypeA("value") }; 
Func(v);

Func 接受参数 object[]

当它不工作时,它会在 lib 深处的某处因空引用而崩溃。

更新整行。也许它比 Func 调用更复杂:

CodeMemberMethod cm = cls.AddMethod(
MemberAttributes.Public,
m.ReturnType,
paramsAndName,
Emit.@stmt(() =>
CodeDom.Call(CodeDom.VarRef("obj"), m.Name)( *** PLACE FOR PARAM HERE*** )
);

最佳答案

这两个方法调用在功能上是相同的。

在第一种情况下,C# 编译器将生成一个变量来保存与第二种情况等效的数组。

考虑以下 C# 代码(在 LinqPad 中):

void Main()
{
CallFunc(new [] { new Foo() });

var foos = new [] { new Foo() };
CallFunc(foos);
}

public class Foo { }

void CallFunc(Foo[] foos) { }

生成的IL:

IL_0001:  ldarg.0     // These first two lines load 1
IL_0002: ldc.i4.1 // for the size of the array
IL_0003: newarr Foo // Create the array of type Foo with the size
IL_0008: stloc.1 // Pops the array into a variable
IL_0009: ldloc.1 // These next two lines load
IL_000A: ldc.i4.0 // the first index (0) of the array
IL_000B: newobj Foo..ctor // Creates a new Foo
IL_0010: stelem.ref // Loads Foo into the array
IL_0011: ldloc.1 // Loads the array onto the stack
IL_0012: call CallFunc // Calls the function
IL_0017: nop // Same thing repeats below with some extra variable loading
IL_0018: ldc.i4.1
IL_0019: newarr Foo
IL_001E: stloc.1
IL_001F: ldloc.1
IL_0020: ldc.i4.0
IL_0021: newobj Foo..ctor
IL_0026: stelem.ref
IL_0027: ldloc.1
IL_0028: stloc.0 // Pops the array into foos
IL_0029: ldarg.0
IL_002A: ldloc.0 // Loads the array from foos
IL_002B: call CallFunc

CallFunc:
IL_0000: nop
IL_0001: ret

Foo..ctor:
IL_0000: ldarg.0
IL_0001: call System.Object..ctor
IL_0006: ret

代码之间的区别是加载和读取 foos 的两条指令。

此 IL 的等效 C# 代码:

var arrayLength = 0;
var foos = new Foo[arrayLength];
var firstIndex = 0;
var foo = new Foo();
foos[firstIndex] = foo;
CallFunc(foos);

关于c# - 函数参数(params object [])有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17504773/

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