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

时间:2012-08-06 06:44:26

标签: c# types casting

我有以下帮助方法:

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

我想在另一个帮手的另一个方法中使用这个方法:

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

但后来我收到了错误:

  

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

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

修改

我知道我可以做两件事:

  • 放宽对CreateRequest或
  • 的约束
  • 加强地图中的约束力。

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

2 个答案:

答案 0 :(得分:5)

对于这种情况,您需要放宽CreateRequest

的通用限制
public static T CreateRequest<T>()
    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 ;
}

这可能会很痛苦,因为您将失去对此参数的编译时验证。

或者,如果您想在其他地方使用CreateRequest方法,则仅为此方案创建非泛型重载。

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 ;
}

答案 1 :(得分:4)

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

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