c# - 将结构传递到接口(interface)字段是否分配?

标签 c# garbage-collection

我有这样的结构

struct MyStructure
    :IFoo
{
}

和这样的方法:

public BarThisFoo(IFoo a)
{

}

我的问题是将结构传递给该方法是否会“装箱”结构,从而导致垃圾分配?

附录: 在有人说之前,垃圾收集在这个应用程序中不是免费的,它实际上对垃圾收集非常敏感,因此分配免费代码很重要。

最佳答案

为了避免装箱,您可以使用带有约束的泛型:

struct MyStructure
    :IFoo
{
}

public void BarThisFoo<T>(T a) where T : IFoo
{

}

参见 J. Richter CLR via C# ,第 2 版,第 14 章:接口(interface),关于泛型和接口(interface)约束的部分。

编辑:

示例代码

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

关于c# - 将结构传递到接口(interface)字段是否分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1816419/

相关文章:

c# - AutoMapper 排除字段

c# - ASP.NET Core 1.0 POST IEnumerable<T> 到 Controller

c# - SomeValue {get;} = true; 之间的区别vs SomeValue => 真;在属性中

garbage-collection - 如果我删除对我订阅的 observable 的所有显式引用,它会被垃圾收集吗?

c# - MySQLAdapter 不会更改值

c# - C# 中的 Snake - 玩家可以缩放窗口 - 将手动缩放的窗口分成相同的正方形

Java 类实例不会被销毁

haskell - Haskell 中的迭代和垃圾收集

java - Android 垃圾收集器

wcf - 垃圾回收后 WCF 中 COM 对象的访问冲突