有没有办法避免在我的扩展方法中传递两个通用参数?

Is there a way to avoid passing two generic parameter in my Extension method?

我有一个 class 类型的 Installer,其中 TModel 有约束。 我想创建一个带有类型签名的扩展方法:\

public static void DoRepetitiveStuff<TOtherObject, TModel>(this Installer<TModel> installer)
where TModel : class, IConstraint, new()
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoSomeStuff<TOtherObject>(c => { });
}

目标是最终我可以使用简单的 installer.DoRepetitiveStuff<TOtherObject>();

调用该函数

出于某种原因,当我在我的其他文件上调用该函数时。它抱怨没有任何扩展方法可以接受现有的安装程序......我需要将它用于:

installer.DoRepetitiveStuff<TOtherObject, TModel>();

有人知道为什么吗?

C# 编译器无法推断出部分通用签名。基本上是全有或全无。为什么?

假设您的代码被接受,然后您创建一个新方法:

public static void DoRepetitiveStuff<TOtherObject>(this Installer installer)
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoOtherStuff();
   installer.DoSomeStuff<TOtherObject>(c => { });
}

现在,您的代码调用了哪个方法?你的还是这个?我们无法知道,因为它是模棱两可的。

为避免这种情况,编译器要么推断 完整 签名,要么根本 none。

作为替代方案,您需要引入另一个可以为您进行推理的 class。然而,在这一点上,实际上更简洁的是只指定两种泛型类型。