我想实例化一个类型将在运行时确定的对象.我还需要对该类型执行显式转换.
大概是这样的:
static void castTest(myEnum val)
{
//Call a native function that returns a pointer to a structure
IntPtr = someNativeFunction(..params..);
//determine the type of the structure based on the enum value
Type structType = getTypeFromEnum(val);
structType myStruct = (structType)Marshal.PtrToStructure(IntPtr, structType);
}
这显然不是有效的代码,但我希望它传达了我想要做的事情的本质.我实际使用的方法必须对大约35种不同的类型执行封送处理操作.我还有其他几个方法需要对同一组类型执行类似的操作.因此,我想将类型确定逻辑从这些方法中分离出来,这样我只需要编写一次,这样方法就可以保持干净和可读性.
我必须承认自己在设计方面完全是个新手.有谁能提出解决这个问题的好办法吗?我怀疑可能有一种我不知道的合适的设计模式.