Array of a generic class with unspecified type

前端 未结 8 778
长发绾君心
长发绾君心 2021-01-11 18:32

Is it possible in C# to create an array of unspecified generic types? Something along the lines of this:

ShaderParam<>[] params = new ShaderParam<&g         


        
8条回答
  •  长发绾君心
    2021-01-11 18:51

    You could use a covariant interface for ShaderParam:

    interface IShaderParam { ... }
    class ShaderParam : IShaderParam { ... }
    

    Usage:

    IShaderParam[] parameters = new IShaderParam[5];
    parameters[0] = new ShaderParam(); // <- note the string!
    
    
    

    But you can't use it with value types like float in your example. Covariance is only valid with reference types (like string 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.

    提交回复
    热议问题