You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何返回泛型委托实现类型参数的柯里化?

C# 泛型参数柯里化实现需求

在C#中如果要对具体类型做柯里化,可以编写如下代码:

Func<int, string> CurryFirstInt(int value) => otherValue => (value + otherValue).ToString();

除此之外,也可以在外层函数上使用泛型,存储首个类型参数的相关信息,示例如下:

interface ISample {
    int Value { get; }
}

Func<int, string> CurryTypeParam<T>(T sample) where T : ISample
    => otherValue => $"{typeof(T).Name}: {sample.Value + otherValue}";

现在我希望返回的委托本身也是泛型的,且携带不同的类型参数,这样就能分两步捕获两个不同的类型参数,无需借助反射。我想要实现的效果大致如下:

delegate string Foo<T>();

Foo CreateFoo<T>()
{
    string FooImp<U>() => $"{typeof(T).Name} / {typeof(U).Name}";
    return FooImp;
}

var foo = CreateFoo<int>();
foo<double>(); // -> "Int32 / Double"
foo<string>(); // -> "Int32 / String"

该需求的动机是使用IServiceCollection注册泛型服务时,对部分类型参数做柯里化,示例场景如下:

interface IFoo<T, U> { }

class Foo<T, U> : IFoo<T, U> { }

delegate IServiceCollection RegisterFoo<T>();

RegisterFoo CreateRegistration<T>(IServiceCollection services)
{
    void Register<U>() => services.AddSingleton<IFoo<T, U>, Foo<T, U>>;

    return Register;
}

var services = new ServiceCollection();
var register = CreateRegistration<int>(services);
register<string>(); // 注册单例IFoo<int, string>,实现类为Foo<int, string>

内容的提问来源于stack exchange,提问作者Jake Conkerton-Darby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 13:09:03