如何为泛型提供默认类型?
我有一个类,当前有几个采用整数参数的方法。 这些整数映射到应用程序可以执行的操作。 我想让该类变得通用,以便该类的使用者可以提供他们拥有的枚举类型以及其中的所有操作,然后这些方法将采用该枚举类型的参数。 但是,我希望他们能够根本不指定泛型类型,并将其默认返回整数,而当前方式的语法没有变化。 这可能吗?
I have a class that currently has several methods that take integer parameters. These integers map to operations that the application can perform. I'd like to make the class generic so that the consumers of the class can provide an enum type that they have with all the operations in it, then the methods will take parameters of that enum type. However, I want them to be able to not specify a generic type at all, and have it default back to integers with no change in syntax from the current way. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
那么...为什么不使用简单继承呢? 就像:
这样你就可以两种方式写:
So... why not use simple inheritance? Like:
This way you can write both ways:
你不能在类的定义中做到这一点:
如果真的重视默认类型 int 的隐式性,你将不得不使用静态工厂方法来做到这一点,尽管我没有看到它的价值。
请参阅下文,了解您如何真正没有从上述内容中受益。
如果你想更进一步,你可以创建一个静态工厂类来解决这个问题,但如果你这样做只是为了提供默认类型,那么这是一个更荒谬的解决方案:
You can't do it in the definition of the class:
If really value the implicitness of the default type being int, you'll have to do it with a static factory method, although I don't see the value of it.
See below for how you really don't benefit from the above.
If you want to take it even farther, you can create a static factory class that will solve this, but that's an even more ridiculous solution if you're doing it for no other reason than to provide a default type:
保留您的原始版本(非通用版本)并创建它的通用版本。
然后从非通用版本调用通用版本。
Keep your original version (non-generic version) and create a generic version of it.
Then call the generic version from your non-generic version.
大多数时候,编译器可以根据传递的参数类型来推断方法上的参数类型:
可以使用 调用
顺便说一句,您也可以拥有泛型方法的非泛型重载。
The compiler can infer the type arguments on methods most of the time based on the type of the arguments passed:
can be called with
By the way, you can have non-generic overloads of a generic method too.
我确信您已经离开了这个,但是我正在解决类似的问题,并发现这个解决方案使用了我不熟悉的“使用”上下文。 他们需要将其放在自己的命名空间中,因此它并不完全完美。
I'm sure you've moved on from this, however I was working through a similar issue and found this solution that uses a context of "using" I was not familiar with. They need to put it in their namespace, so its not completely perfect.
编译器大多数时候可以根据传递的参数类型推断字段上的类型参数:
可以用作,
并且应该导致,
The compiler can infer the type arguments on fields most of the time based on the type of the arguments passed:
can be used as,
and that should result into,