[英]generic method with multiple type parameters in c#
以为我在做一些简单的事情,但是以某种方式无法编译。
protected List<R> Retrieve<R>(T request)
我想编写一个通用方法,该方法可以根据请求类型返回不同的响应。 因此,当我调用Web api网站时,可能会收到不同的强类型请求,但是在此功能中,我将进行json序列化,发送请求并反序列化响应。
看起来C#不允许我这样做。 有没有解决方法,或者我将需要为每个请求编写不同的方法。
由于您使用两个不同的类型参数,因此必须定义其中两个
protected List<R> Retrieve<T, R>(T request)
注意,可以在类型(类/结构)级别上声明它们之一或全部。
class C<T>
{
protected List<R> Retrieve<R>(T request)
{
return default;
}
}
这相当于像这样声明的Func Delegate
public delegate TResult Func<in T,out TResult>(T arg);
我可以看到的唯一方法是使用如下约束:
// This is to constrain T in your method and call ToRType()
public interface IConvertableToTReturn
{
object ToRType(object input);
}
protected List<TReturn> DoSomethingAwesome<T, TReturn>(T thing)
where T : IConvertableToTReturn
{
// Do what you need to do. (Return with thing.ToRType())
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.