通用Type参数没有装箱或类型参数转换

我有以下帮助方法:

public static T CreateRequest() where T : Request, new() { T request = new T(); // ... // Assign default values, etc. // ... return request; } 

我想从另一个帮助器中的另一个方法内部使用此方法:

 public T Map(F value, T toValue) where T : new() where F : new() { if (typeof(T).BaseType.FullName == "MyNamespace.Request") { toValue = MyExtensions.CreateRequest(); } else { toValue = new T(); } } 

但后来我得到了错误:

类型’T’不能在generics类型或方法’MyExtensions.CreateRequest()’中用作类型参数’T’。 从’T’到’MyNamespace.Request’没有装箱转换或类型参数转换。

有没有办法转换类型“T”,以便CreateRequest将使用它没有问题?

编辑:

我知道我可以做两件事:

  • 放宽对CreateRequest的约束或
  • 收紧地图中的约束。

但是我不能做第一个,因为在CreateRequest中我是Request类的用户属性,而我不能做第二个,因为我使用其他类型(不从Requestinheritance)和Map函数。

对于这种情况,您需要放松CreateRequest通用限制。

 public static T CreateRequest() where T : new() { if(!typeof(Request).IsAssignableFrom(typeof(T))) throw new ArgumentException(); var result = new T(); Request request = (Request)(object)result; // ... // Assign default values, etc. // ... return result ; } 

这可能会很痛苦,因为您丢失了此参数的编译时validation。

或者,如果要在其他位置使用CreateRequest方法,则仅为此方案创建非generics重载。

 public static object CreateRequest(Type requestType) { if(!typeof(Request).IsAssignableFrom(requestType)) throw new ArgumentException(); var result = Activator.CreateInstance(requestType); Request request = (Request)result; // ... // Assign default values, etc. // ... return result ; } 

您已声明T的类型是CreateRequest方法中的Request ; 另一方面,在Map方法中你没有这样的约束。 尝试将Map的声明更改为:

 public T Map(F value, T toValue) where T : Request, new() where F : new()