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
相关产品推荐
相关产品推荐

