简体   繁体   English

当使用相互约束的类型参数调用通用扩展方法时,不能省略扩展类型参数

[英]Can't omit the extension type argument when calling generic extension method with mutually constrained type parameters

public static class Utility {
  public static void ShadowDeserializeFile<T, S>(this T target, FileInfo file)
  where T : ShadowDeserializable<S> {
    S shadow = SomeHelpingMethod(file);
    target.ShadowDeserialize(shadow);
  }
}
public interface ShadowDeserializable<S> {
  void ShadowDeserialize(S shadow);
}

With above code I expect I can call it like: 使用上面的代码,我希望可以这样称呼它:

var something = new SomeType(); //SomeType implements ShadowDeserializable<ShadowType>
something.ShadowDeserializeFile<ShadowType>(aFileInfoObj);

However Visual Studio issues error saying that using the generic method requires 2 type arguments. 但是,Visual Studio发出错误,指出使用通用方法需要2个类型参数。 Only when calling as below it compiles: 仅在按以下方式调用时才编译:

something.ShadowDeserializeFile<SomeType,ShadowType>(aFileInfoObj);

I tried switching the order of type parameters in the method declaration, no difference. 我尝试在方法声明中切换类型参数的顺序,没有区别。

How should I modify the declaration so that it could be called concisely as I expected? 我应该如何修改声明,使如我所料它可以被称为简洁?

Or is my expectation simply wrong as the extension type argument simply can't be omitted in this case? 还是我的期望仅仅是错误的,因为在这种情况下不能忽略扩展类型参数?

There is no way to infer type of one parameter and specify another explicitly.You need to specify both types.Another option is to add a parameter of type S and then compiler will infer the second parameter's type for you based on what you pass to the method.Then you can call it without specifying any type. 无法推断一个参数的类型并显式指定另一个参数,您需要同时指定两种类型。另一种选择是添加类型为S的参数,然后编译器将根据传递给参数的内容为您推断第二个参数的类型。方法。然后您可以在不指定任何类型的情况下调用它。 But if you don't need such parameter, specifying two types is the only option. 但是,如果不需要这样的参数,则指定两种类型是唯一的选择。

If specifying one parameter where two type is expected would be possible, it would cause ambiguity.Imagine what would happen if you have another method with the same name that has one generic argument. 如果指定一个参数,其中两个类型,预计将成为可能,这将导致ambiguity.Imagine如果你有有一个一般的参数名称相同的另一种方法会发生什么。

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

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