使用反射从属性类型获取字节数
本文关键字:获取 字节数 类型 从属性 反射 | 更新日期: 2023-09-27 18:33:49
我有一个函数来确定记录值的字段大小(以字节为单位)。如果是字符串,我使用 Length 返回字节数。如果它不是字符串,我调用另一个使用开关分配字节数的方法。
这是我所拥有的:
private int getRecordFieldSize(PropertyInfo recordField,DataRecord dataRecord)
{
if (recordField.PropertyType.ToString() == "System.String")
{
return recordField.GetValue(dataRecord,null).ToString().Length;
}
else
{
int bytesOfPropertyType = getBytesBasedOnPropertyType(recordField.PropertyType.ToString());
return bytesOfPropertyType;
}
}
private int GetBytesBasedOnPropertyType(string propType)
{
switch(propType)
{
case "System.Boolean":
return 1;
case "System.Byte":
return 1;
case "System.SByte":
return 1;
case "System.Char":
return 1;
case "System.Decimal":
return 16;
case "System.Double":
return 8;
case "System.Single":
return 4;
case "System.Int32":
return 4;
case "System.UInt32 ":
return 4;
case "System.Int64":
return 8;
case "System.UInt64":
return 8;
case "System.Int16":
return 2;
case "System.UInt16":
return 2;
default:
Console.WriteLine("'nERROR: Unhandled type in GetBytesBasedOnPropertyType." +
"'n't-->String causing error: {0}", propType);
return -1;
}
}
我的问题:有没有办法避免使用 switch 语句来分配字节?
我觉得应该有某种方法可以使用反射获取字节数,但我在 MSDN 上找不到任何东西。
我真的是 C# 的新手,所以请随时将我的代码拆开。
谢谢
两种可能的解决方案:
-
Marshal.SizeOf() 方法 (http://msdn.microsoft.com/en-us/library/y3ybkfb3.aspx)
-
大小关键字 (http://msdn.microsoft.com/en-us/library/eahchzkf%28VS.71%29.aspx)
后者仍然需要一个switch语句,因为它是不可能的:
int x;
sizeof(x);
sizeof 仅适用于明确声明的类型,例如 sizeof(int)
因此,在这种情况下,(1)是您更好的选择(它将适用于所有类型,而不仅仅是switch语句中的类型)。
这可能会
有所帮助
private int getRecordFieldSize(PropertyInfo recordField,DataRecord dataRecord)
{
if (recordField.PropertyType.ToString() == "System.String")
{
return recordField.GetValue(dataRecord,null).ToString().Length;
}
else
{
int bytesOfPropertyType = System.Runtime.InteropServices.Marshal.SizeOf(recordField.PropertyType);
return bytesOfPropertyType;
}
}