如何将T转换为类以匹配"where T:class"约束?

Lau*_*nce 5 c# generics constraints

在处理通用依赖注入处理程序(基本服务定位器)时,我遇到了泛型问题.

编辑1(为清晰起见)

好的,所以我实际上使用SimpleInjector作为DI解析器,它对它的GetInstance方法有类约束,所以这里有一些更完整的代码:

  public T GetInstance<T>() where T : class
  {
     try
     {
        // works
        return _container.GetInstance<T>();
     }
     catch( ActivationException aEx )
     {
        return default( T );
     }
  }

  public T GetInstance<T>()
  {
     try
     {
        if( typeof( T ).IsClass )
        {
           // does not work, T is not a reference type
           return _container.GetInstance<T>();
        }
     }
     catch( ActivationException aEx )
     {
        return default( T );
     }
  }
Run Code Online (Sandbox Code Playgroud)

编辑2 - 最终代码,因为它在评论中看起来很奇怪:

  public T GetInstance<T>()
  {
     try
     {
        if( typeof( T ).IsClass )
        {
           return (T) _container.GetInstance(typeof(T));
        }
     }
     catch( ActivationException aEx )
     {
        return default( T );
     }
  }
Run Code Online (Sandbox Code Playgroud)

use*_*301 1

您可以使用另一种辅助方法吗?请在下面找到测试类

public class Test
{
  public T GetInstance<T>() where T : class
  {
    return (T)GetInstance(typeof(T));
  }

  private object GetInstance(Type type) 
  {
     return Activator.CreateInstance(type);
  }

  public T GetEvenMoreGenericInstance<T>()
  {
     if( !typeof( T ).IsValueType )
     {
        return (T)GetInstance(typeof(T));
     }
     return default( T );
  }
}
Run Code Online (Sandbox Code Playgroud)