我正在创建一个联网的应用程序。 为此,我正在创建一个消息传递系统。 到目前为止我得到了什么(至少是一个片段......)
public static byte[] ClassToBytes(GenericMessage Data)
{
int Size = Marshal.SizeOf(Data);
byte[] Buffer = new byte[Size];
IntPtr Ptr = Marshal.AllocHGlobal(Size);
Marshal.StructureToPtr(Data, Ptr, true);
Marshal.Copy(Ptr, Buffer, 0, Size);
Marshal.FreeHGlobal(Ptr);
return Buffer;
}
public static GenericMessage BytesToClass(byte[] Source, ClassType Type)
{
switch (Type) //This is going to be extended
{
case ClassType.GenericMessage:
return BytesToClass<GenericMessage>(Source);
break;
case ClassType.RequestMessage: //RequestMessage is derived from GenericMessage
return BytesToClass<RequestMessage>(Source);
break;
case ClassType.ResponseMessage: //ResponseMessage is derived from GenericMessage
return BytesToClass<ResponseMessage>(Source);
break;
default:
throw new KeyNotFoundException();
break;
}
}
public static T BytesToClass<T>(byte[] Source)
{
int Size = Marshal.SizeOf(typeof(T));
IntPtr Ptr = Marshal.AllocHGlobal(Size);
Marshal.Copy(Source, 0, Ptr, Size);
T result = (T)Marshal.PtrToStructure(Ptr, typeof(T));
Marshal.FreeHGlobal(Ptr);
return result;
}
基本上我想做的是:
public static GenericMessage BytesToClass(byte[] Source, ClassType Type)
{
return BytesToClass<Type>(Source);
}
是否有这样的方式使用枚举,或者字典?
我已经尝试过,但没有任何结果。
答案 0 :(得分:2)
如果你想动态提供泛型类型,就像评论中评论的@usr一样,你可以这样做:
public static GenericMessage BytesToClass(byte[] Source, ClassType MyType)
{
// Gets the Type we want to convert the Source byte array to from the Enum
Type _targetType = typeof(Program).GetNestedType(MyType.ToString());
// Gets the generic convertion method, note we have to give it the exact parameters as there are 2 methods with the same name
var _convMethod = typeof(Program).GetMethod("BytesToClass", new Type[] { typeof(byte[]) });
// Invoke the generic method, setting T as _targetType
var result = _convMethod.MakeGenericMethod(new Type[] { _targetType }).Invoke(null, new object[] { Source });
return (GenericMessage)result;
}
ClassType
enum
成员的名称必须与他们所代表的类名完全相同。
此外,此方法假定您要将字节数组转换为的类在Program
类中(请参阅typeof(Program)
)。显然你应该改变它以使它适用于你的程序。