[英]Using parameter of generic type in generic method of interface
我的朋友。 我是 generics 的新手,但想使用通用方法 (FooAsync) 创建接口(让它成为 IFooAsync),该方法获取另一个泛型类型(具有定义 Process)的参数,但我不想包含这个 U 类型方法定义。 怎么做才对? 我的代码现在看起来像这样(我使用 Object 作为通用 Progress 类型,但肯定这是一个糟糕的解决方案):
public interface IFooAsync
{
System.Threading.Tasks.Task<List<T>> FooAsync<T>(
// Some parameters, that my method gonna take.
System.IProgress<Object> progress,
System.Threading.CancellationToken cancellationToken) where T : new();
}
你可以做
using System;
using System.Threading;
using System.Threading.Tasks;
public interface IFooAsync<TReturn> where TReturn : new()
{
Task<List<TReturn>> FooAsync<TProgress>(IProgress<TProgress> progress,
CancellationToken cancellationToken);
}
这意味着您在调用方法时不必指定两个类型参数,因为编译器可以推断它们。
例如
IFooAsync<string> myFoo = ... ;
IProgress<int> myProgress = ... ;
List<string> result = await myFoo.FooAsync(myProgress, CancellationToken.None);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.