通常,将结构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)