避免在泛型类中装箱和拆箱

Nel*_*mel 6 c# generics boxing unboxing

下面是一些快速代码来说明我的问题.有什么方法可以避免这种明显不必要的拳击/拆箱?

public class TestClass<T>
{
  public T TestMethod()
  {
    if (typeof(T) == typeof(bool))
    {
      return true; // doesn't work
      return (T)(object)true; // works, but any way to avoid this?
    }

    return default(T);
  }
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 4

这是处理您在这里所做的事情的唯一方法(为特定的封闭泛型类型返回非默认值)。