Are there other ways of calling an interface method of a struct without boxing except in generic classes?

前端 未结 2 411
太阳男子
太阳男子 2021-02-02 00:54

see code snippet

public interface I0
{
    void f0();
}
public struct S0:I0
{
    void I0.f0()
    {

    }
}
public class A where E :I0
{
    public E          


        
2条回答
  •  被撕碎了的回忆
    2021-02-02 01:16

    Since interfaces are treated as reference types, there is no way to call a method on a struct referred to by an interface without having to box the underlying struct first.

    When using a generic method enforcing the type to implement the interface, the C# compiler simply lifts the actual implementation details and hence the calling convention to the runtime. Luckily the C# compiler is smart enough to instruct the JIT compiler that the subjected type does implement interface X and might be a struct. With this information the JIT compiler can figure out how to invoke method Y declared by interface X.

    The above trick is not usable for a non-generic method call since there is no practical way for the JIT compiler to figure out the actual type represented by the argument X when X is a non sealed class or interface. Hence, there is no way for the C# compiler to generate JIT that deals with a lookup table in case the type represented by the interface passed is a non-sealed class and a direct method invocation that deals with structs and sealed classes.

    When using dynamic you can, in theory, prevent boxing however the loss of performance for introducing the DLR will likely yield no benefit at all.

提交回复
热议问题