相关疑难解决方法(0)

在这种情况下,C#泛型是否会阻止结构的自动装箱?

通常,将结构S视为接口I会触发结构的自动装箱,如果经常这样做会对性能产生影响.但是,如果我编写一个带有类型参数的泛型方法并用a T : I调用它S,那么编译器是否会省略装箱,因为它知道类型S并且不必使用接口?

这段代码显示了我的观点:

interface I{
    void foo();
}

struct S : I {
    public void foo() { /* do something */ }
}

class Y {

    void doFoo(I i){
        i.foo();
    }
    void doFooGeneric<T>(T t) where T : I {
        t.foo(); // <--- Will an S be boxed here??
    }

    public static void Main(string[] args){
        S x;
        doFoo(x); // x is boxed
        doFooGeneric(x); // x is not boxed, at least …
Run Code Online (Sandbox Code Playgroud)

c# generics autoboxing interface

10
推荐指数
1
解决办法
417
查看次数

标签 统计

autoboxing ×1

c# ×1

generics ×1

interface ×1