我有一个像这样的结构
struct MyStructure
:IFoo
{
}
和这样的方法:
public BarThisFoo(IFoo a)
{
}
我的问题是将结构传递到该方法中是否会“装箱”结构,从而导致垃圾分配?
附录:
在有人说之前,垃圾收集在这个应用程序中并不是免费的,它实际上对垃圾收集非常敏感,因此免费分配的代码很重要。
为了避免装箱,您可以使用带有约束的泛型:
struct MyStructure
:IFoo
{
}
public void BarThisFoo<T>(T a) where T : IFoo
{
}
See J. Richter 通过 C# 进行 CLR https://rads.stackoverflow.com/amzn/click/com/0735621632,第二版,第 14 章:接口,有关泛型和接口约束的部分。
EDIT:
示例代码
using System;
using System.Collections;
interface IFoo {
void Foo();
}
struct MyStructure : IFoo {
public void Foo() {
}
}
public static class Program {
static void BarThisFoo<T>(T t) where T : IFoo {
t.Foo();
}
static void Main(string[] args) {
MyStructure s = new MyStructure();
BarThisFoo(s);
}
}
Main 方法的 IL 代码不包含任何框指令:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 15 (0xf)
.maxstack 1
.locals init ([0] valuetype MyStructure s)
IL_0000: ldloca.s s
IL_0002: initobj MyStructure
IL_0008: ldloc.0
IL_0009: call void Program::BarThisFoo<valuetype MyStructure>(!!0)
IL_000e: ret
} // end of method Program::Main
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)