简体   繁体   English

如何为通用接口创建具有其他类型的通用扩展方法

[英]How to create a generic extension method with additional type for generic interface

Today I encountered a small problem, and unfortunately I have not found a good solution. 今天,我遇到了一个小问题,不幸的是我没有找到一个好的解决方案。 I would like to create a extension method for some generic interface. 我想为某些通用接口创建扩展方法。 This method accepts a different type of a generic parameter, as seen below 此方法接受不同类型的通用参数,如下所示

public interface IGenericInterface<TSource>
{
    void DoSomething<TDest>();
}

DotNetFiddle 点网提琴

How to call a DoSomething2 method exactly in the same way as DoSomething method (without passing first type)? 如何以与DoSomething2方法完全相同的方式调用DoSomething方法(不传递第一个类型)?

public void DoSomething<TDest>()
//Called like below
testClass.DoSomething<object>();

instead of (like my current signature) 而不是(例如我当前的签名)

public static void DoSomething2<TDest, TSource>(this IGenericInterface<TSource> interf)
//called like below
testClass.DoSomething2<string, object>(); // have to repass object type

I know that the compiler can not automatically infer the second type ( link ). 我知道编译器无法自动推断第二种类型( link )。 But I'm curious if anyone has found a solution. 但是我很好奇是否有人找到了解决方案。

Your problem is the argument - you're depending on type inference to handle the first generic type, but then you want to explicitly specify the second one - that just isn't possible in C#. 您的问题是参数-您要依靠类型推断来处理第一个泛型类型,但随后您要显式指定第二个泛型类型-这在C#中是不可能的。

Instead, why not change the type of the argument? 相反,为什么不更改参数的类型呢?

public static void DoSomething3<T, T2>(this IGenericInterface<T> interf, T2 parameter)
//called like below
testClass.DoSomething3((object)3);

With this, T is inferred based on testClass (as long as it's not ambiguous), and T2 is inferred based on (object)3 . 这样, T是根据testClass推断的(只要它不是模棱两可),而T2是根据(object)3推断的。

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

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