将枚举值连接到方法组的优雅方式
本文关键字:方式 方法 枚举 连接 | 更新日期: 2023-09-27 18:06:10
我正在创建一个网络应用程序。为此,我创建了一个信息系统。到目前为止我得到的(至少是一个片段…)
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);
}
对于枚举或者字典是否有这样的方法?
我已经试过了,但是没有任何结果。
如果您想动态地提供泛型类型,就像@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)
)中的类。显然,您应该更改它以使其与您的程序一起工作。