我的问题非常类似于:Cast to type known only at runtime ,但是那个问题并没有得到真正的回答(它也是用 C 而不是 C#)。
我正在写一些东西来控制一些硬件,并且根据给定的硬件配置,我必须用“byte”或“UInt32”类型做一些按位运算。位算术代码很长,但在 32 位和 8 位情况下是相同的,唯一的区别是某些循环的长度(32 或 8)。
我目前的解决方案是使用开关,这意味着我在一个巨大的 if 语句中有几乎相同代码的两个副本。
另一种解决方案是使用数组或 0 和 1 而不是 UInt32 或字节来执行按位运算,然后在最后转换为 UInt32 或字节。
我在这里最感兴趣的最后一个解决方案是动态选择我将在运行时使用的类型。这是我想要的一些伪代码:
System.Type MyType;
if (something)
MyType=type1;
else
MyType=somethingElse;
myType someVariable; //Create a variable of type myType. This line will give an
//error
someVariable=(myType) otherVariable //do an example typecast with the
//runtime-determined type
我四处搜索知道答案可能与泛型和反射有关,但我无法弄清楚如何做到这一点。
最佳答案
您可以考虑使用 BitArray为此 - 您可以从字节或 uint32 初始化它,进行按位运算,然后在最后将其转换回例如
object value;
bool isByte = value is byte;
BitArray ba = isByte
? new BitArray(new byte[] { (byte)value })
: new BitArray(BitConverter.GetBytes((unint32)value));
...
关于c# - 创建仅在运行时已知类型的变量 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16723001/