简体   繁体   English

在接口的泛型方法中使用泛型类型的参数

[英]Using parameter of generic type in generic method of interface

my friends.我的朋友。 I'm new to generics, but want to create interface (let it be IFooAsync) with generic method (FooAsync) that gets parameter of another generic type (that has definition Process), but I don't want to include this U type in method definition.我是 generics 的新手,但想使用通用方法 (FooAsync) 创建接口(让它成为 IFooAsync),该方法获取另一个泛型类型(具有定义 Process)的参数,但我不想包含这个 U 类型方法定义。 How to do that right?怎么做才对? My code now looks like this (I've used Object as generic Progress type, but sure it's an awful solution):我的代码现在看起来像这样(我使用 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();
}

You could do你可以做

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

which means you don't have to specify two type paremeters when calling the method as the compiler can infer them.这意味着您在调用方法时不必指定两个类型参数,因为编译器可以推断它们。

eg例如

IFooAsync<string> myFoo = ... ;
IProgress<int> myProgress = ... ;

List<string> result = await myFoo.FooAsync(myProgress, CancellationToken.None);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM