简体   繁体   English

有没有一种方法可以为一个通用类提供多个签名

[英]Is there a way to have multiple signatures for a generic class

I have a generic class with a complex signature that I would like to simplify for convenience if all of the type parameters will be the same. 我有一个带有复杂签名的通用类,为方便起见,如果所有类型参数都相同,我想简化一下。

MyClass<T1, T2, T3, T4>

If all of the type parameters are Guid, I'd like to supply just one type parameter, the only way I can think of doing it would be to have another class defined. 如果所有类型参数都是Guid,我只想提供一个类型参数,那么我想到的唯一方法就是定义另一个类。

MyClass<T1> : MyClass<T1, T1, T1, T1>

Is there a better method of achieving this functionality? 有没有更好的方法来实现此功能? Ultimately, I don't want there to be anything different between the classes other than the ability to use a simplified signature. 最终,除了使用简化签名的能力之外,我不希望类之间有任何不同。

Unfortunately, there is generally no way for the compiler to infer generic type parameters based on other generic type parameters. 不幸的是,编译器通常无法基于其他通用类型参数来推断通用类型参数。 Therefore, you either have to specify all or nothing. 因此,您必须指定全部或不指定任何内容。 If you refer to a class, you always have to specify all type parameters. 如果引用一个类,则始终必须指定所有类型参数。

However, the compiler may have a chance to infer generic type parameters of methods from the passed parameters, so what you can do is something like 但是,编译器可能会从传递的参数中推断出方法的泛型类型参数,因此您可以执行以下操作

public MyClass<T, T, T, T> CreateMyClass<T>(T item)

If you provide an API like that so users don't have to rely on constructors, you may have a chance to keep explicit type parameters to a bare minimum. 如果您提供这样的API,以便用户不必依赖构造函数,则可能有机会将显式类型参数保持在最低限度。

No. This is the only way. 不,这是唯一的方法。 As far as the compiler is concerned, T1 , T2 , T3 and T4 are unrelated. 就编译器而言, T1T2T3T4不相关。

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

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