Boxing when using generics in C#

前端 未结 2 960
梦如初夏
梦如初夏 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 01:01

    I believe it's the generic method constraint that does this to you - but...

    In any case, there's no need for the generic method at all. Just write it as:

    public void Add(Person person)
    {
        m_stack.Push(person);
    }
    

    You'll find that the IL gets simplified, and completely avoids the issue. If you're constraining to a specific reference type, you can just use that reference type.

    This is much easier to understand, and much more clear. I'd suggest avoiding the generic method call unless it's really needed. Generic methods make the class less obvious, which means less readable and maintainable in the long run, and more difficult to use.

提交回复
热议问题