c# - Fluent API 的类型推断

标签 c# generics fluent fluent-interface

我有以下扩展方法:

public static IFoo Foo(this IFluentApi api, Action action);

public static IFoo<TResult> Foo<TResult>(
    this IFluentApi api, Func<TResult> func);

public static IBar Bar(this IFoo foo);

public static void FooBar(this IBar bar, Action action);

public static void FooBar<TResult>( // <- this one cannot work as desired 
    this IBar bar, Action<TResult> action);

通用接口(interface)总是派生自它们对应的非通用接口(interface)。

不幸的是,要完成这项工作:

api.Foo(x => ReturnLong())
   .Bar()
   .FooBar(x => ...); // x should be of type long

我还需要实现以下扩展方法:

public static IBar<TResult> Bar<TResult> (this IFoo<TResult> foo);

并将上述扩展方法的最后一个更改为:

public static void FooBar<TResult>(
    this IBar<TResult> bar, Action<TResult> action);

实际上,我不仅在 Foo()FooBar() 之间有 Bar(),而且还有很长的方法链有巨大的额外实现成本。

有什么方法可以避免这个问题并“神奇地”转发TResult泛型参数吗?

编辑:

不会丢失类型推断!

最佳答案

假设您可以从 IFoo<TResult> 开始到IFoo并且您的方法链不关心 TResult您可以通过将用法更改为类似以下内容来节省一些实现:

api.Foo(x => ReturnLong())
   .Bars(foo=>foo.Bar1() //where foo is an IFoo
                 .Bar2()
                 .Bar3()
                 ...
    )
   .FooBar(x => ...);

关于c# - Fluent API 的类型推断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17842553/

相关文章:

c# - 替换关联实体

swift - 在参数类型 '[ItemA]' 中, 'ItemA' 不符合预期类型 'Sortable'

java - 执行通用 Java 类

java - <?> 和 <?> 之间的区别扩展对象>

kubernetes - 如何将日志从运行在 GCP 之上的 Kubernetes 上的 pod 发送到 elasticsearch/logstash?

c# - 是否可以在对象列表中找到对象的类?

C# 浏览表单

mysql - Mono、mysql、fluent nhibernate 和 TdsInternalException

c - 从 Windows 到 Linux 的语法错误 Fluent UDF

c# - C++ 指针与 C# 指针