Luc*_*uca 1 c# generics casting
我有一个C#方法,我试图generics用作:
unsafe private void PerformWindowLevel<T>(int lower, int upper, ref T[] pixels)
Run Code Online (Sandbox Code Playgroud)
在函数的某处,我有以下几行:
float shift = ... // some value
float scale = ... // some value
float val = ((float)pixels[i] + shift) * scale;
Run Code Online (Sandbox Code Playgroud)
我在这里得到错误Cannot convert type 'T' to 'float'.
该方法称为:
PerformWindowLevel<byte>(10, 100, ref pixels);
Run Code Online (Sandbox Code Playgroud)
所以我将一个byte类型转换为float,这应该是可能的.pixels是一个声明为public byte[] pixels;并填充有效值的字节数组.
问题是,你T不知道它在你的调用代码中可能是什么,它只是一个通用的类型参数,也可能是string你(显然)无法投射到的任何东西float.您需要一个通用约束:
unsafe private void PerformWindowLevel<T>(int lower, int upper, ref T[] pixels) where T: float
Run Code Online (Sandbox Code Playgroud)
这仍然不起作用,因为你不能使用struct(float是)作为泛型类型参数.只允许接口或类.
然而,这只能float成为一个有效的通用参数,使得术语通用 - 非常 - 非通用.这就是为什么泛型在你的情况下是完全错误的.当只有一种或两种类型可能时,您应该为该特定类型创建具体方法(或重载).另一方面的泛型声明每种类型(满足由a表示的通用约束where)是可能的,而不仅仅是一种.