未指定类型的泛型类的数组
在 C# 中是否可以创建未指定泛型类型的数组?大概是这样的:
ShaderParam<>[] params = new ShaderParam<>[5];
params[0] = new ShaderParam<float>();
或者由于 C# 的强类型,这根本不可能?
Is it possible in C# to create an array of unspecified generic types? Something along the lines of this:
ShaderParam<>[] params = new ShaderParam<>[5];
params[0] = new ShaderParam<float>();
Or is this simply not possible due to C#'s strong typing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是不可能的。在泛型类型在您的控制之下的情况下,您可以创建一个非泛型基本类型,例如,
我的猜测是,这是您无法控制的 XNA 类型。
It's not possible. In the case where the generic type is under your control, you can create a non-generic base type, e.g.
My guess is that this is an XNA type you have no control over though.
您可以为
ShaderParam
使用协变接口:用法:
但是您不能将其与
float等值类型一起使用
在你的例子中。协方差仅对引用类型有效(例如 my 示例中的string
)。如果类型参数出现在逆变位置(例如作为方法参数),您也不能使用它。尽管如此,了解这项技术可能还是有好处的。You could use a covariant interface for
ShaderParam<T>
:Usage:
But you can't use it with value types like
float
in your example. Covariance is only valid with reference types (likestring
in my example). You also can't use it if the type parameter appears in contravariant positions, e.g. as method parameters. Still, it might be good to know about this technique.游戏已经很晚了,但方法如下: http://www.codeproject.com/Articles/1097830/Down-the-Rabbit-Hole-with-Array-of-Generics
Rather late to the game, but here's how: http://www.codeproject.com/Articles/1097830/Down-the-Rabbit-Hole-with-Array-of-Generics
那没有意义。
如果您编写
params[3]
会发生什么?会是什么类型呢?
您可能想要创建一个非泛型基类或接口并使用它们的数组。
That wouldn't make sense.
What would happen if you write
params[3]
?What type would it be?
You may want to create a non-generic base class or interface and use an array of them.
这在定义 T 的通用类或通用扩展方法中是可能的:
This is possible in a generic class or a generic extension method where T is defined:
不,对于实例化类型而言,ShaderParam 概念是没有意义的。换句话说,具体的
ShaderParam
不是ShaderParam
的实例。因此,声明的数组类型对于保存该实例是非法的。 (除此之外,它本身就已经是非法语法了。)No, the concept
ShaderParam<>
is meaningless as far as an instantiated type is concerned. In other words, a concreteShaderParam<float>
is not an instance ofShaderParam<>
. Therefore, the declared type of the array would be illegal for holding that instance. (Above and beyond the fact that it's already illegal syntax to begin with.)不直接。封闭泛型是幕后的特定“类型”,因此即使是开放泛型也太笼统,无法成为“强类型”。
我能想到的最好的解决方案(我之前使用过)是为泛型类创建一个非泛型祖先。该解决方案是否有效取决于您计划使用该阵列做什么。
Not directly. A closed generic is a specific "type" behind the scenes, so even an open generic is too general to be a "strong type".
The best solution I can think of, which I've used before, is to create a non-generic ancestor to the generic class. Whether that solution will function depends on what you plan to use the array for.
创建未指定泛型类型的数组:
如果您需要对对象执行某些特定于类型的操作,您可以使用反射
希望这会有所帮助。
create an array of unspecified generic types:
If you need to perform some type specific actions on the object you could use Reflection
Hope this helps.