0

我有一类安装程序类型,其中 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>();

任何人都知道为什么?

4

1 回答 1

2

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

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

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

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

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

作为替代方案,您需要引入另一个可以为您进行推理的类。但是,此时,仅指定两种泛型类型实际上更简洁。

于 2020-02-18T17:23:22.233 回答