Boxing when using generics in C#

前端 未结 2 964
梦如初夏
梦如初夏 2020-12-19 00:16

I have the following simple C# code:

private Stack m_stack = new Stack();

public void Add(T obj)
  where T : Person
{
          


        
2条回答
  •  Happy的楠姐
    2020-12-19 00:58

    Excerpt from Ecma-335 Partition III 4.1

    If typeTok is a reference type, the box instruction does nothing.

    where typeTok is !!T in your case.

    My guess is that when the compiler compiles the code, it always calls box regardless whether the type of the operand is reference type or not. Because of the semantic of the box instruction, the desired result is always guaranteed.

提交回复
热议问题