我正在尝试编写泛型方法,它应该通过使用隐式转换运算符将
JToken
解析为具体类型。public static implicit operator CategoryDto(JToken token)
{
var result = new CategoryDto
{
//Mapping here
};
泛型方法:
public static T ParseResult<T>(this JToken response, string relationship) where T : class, new()
{
//Implicit operator is triggered, fields were mapped as expected
CategoryDto concreteResult = response["value"];
//Line below doesn't trigger my custom conversion, even when T is CategoryDto
T result = response["value"];
return result;
}
我希望我的
result
变量将根据隐式运算符进行映射 - 但没有任何反应,即使我将 CategoryDto
作为 T
参数传递 - T
是 CategoryDto
具有默认值。
我不明白为什么这个片段不起作用(可能是由于缺乏关于多态性/泛型类型的知识)。
它与泛型类型的编译/运行时行为有关吗?
编译器不允许编译这个,因为这不是类型安全的。
T
可以是与约束匹配的任何类型,并且无法保证存在从 T
的显式转换。通常你会想要依赖实际的 json 解析(可能使用一些自定义转换器),例如:
public static T ParseResult<T>(this JToken response, string relationship) where T : class, new()
=> response["value"].ToObject<T>();
如果你真的想利用隐式转换(尽管我不建议这样做)你可以这样做:
public static T ParseResult<T>(JToken response, string relationship) where T : class, new()
{
if (typeof(T) == typeof(CategoryDto))
return (T)(object)(CategoryDto)response["value"];
return response["value"].ToObject<T>();
}
在.NET 7中你可以使用静态抽象接口成员:
public interface IImplicitlyConvertableFromJToken<T> where T : IImplicitlyConvertableFromJToken<T>
{
static abstract implicit operator T(JToken token);
}
class CategoryDto : IImplicitlyConvertableFromJToken<CategoryDto>
{
public static implicit operator CategoryDto(JToken token)
{
var result = new CategoryDto
{
//Mapping here
};
return result;
}
}
public static T ParseResult<T>(JToken response, string relationship) where T : class, IImplicitlyConvertableFromJToken<T>, new()
=> response["value"];