简体   繁体   English

仅传递定义其他泛型的一种泛型类型

[英]Passing only one generic type which defines the other generics

I have the following method:我有以下方法:

public void SomeMethod<TParser, T1, T2> () where TParser : IParser<T1, T2>, new() 
{
   ...
}

and an IParser<T1, T2> interface and a class which implements it:和一个IParser<T1, T2>接口和一个实现它的类:

public interface IParser<T1, T2>
{
   ...
}

public class Parser : IParser<string, int>
{
   ...
}

Now my questions is would it be possible to only pass TParser to the method, since there is a constraint set which kinda defines T1 and T2 .现在我的问题是是否可以只将TParser传递给该方法,因为有一个约束集定义了T1T2 So would it be possible to do something like the following:那么是否可以执行以下操作:

SomeMethod<Parser>();

I would guess it isn't possible, but would there be something similar?我想这是不可能的,但会不会有类似的东西?

What you can do is to define a non-generic version of your interface.您可以做的是定义接口的非通用版本。 And derive your generic interface from it and use non-generic version as a constraint.并从中派生出您的通用接口,并使用非通用版本作为约束。 And if you have parameters of type T1 and T2 this won't be useful.如果您有T1T2类型的参数,这将没有用。

internal interface IParser
{
... // if you can define any. or it can be empty also
}

public interface IParser<T1, T2> : IParser
{
   ...
}

And change your method signature to this :并将您的方法签名更改为:

public void SomeMethod<TParser> () where TParser : IParser new() 
{
   ...
}

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

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