2013-10-03 22 views
0

我有一個函數可以確定記錄值的字段大小(以字節爲單位)。如果它是一個字符串,我使用Length來返回數字字節。如果它不是字符串,我會調用另一種方法來使用開關來分配字節數。使用反射來獲取來自PropertyType的字節數

以下是我有:

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#真的很陌生,所以請隨意將我的代碼拆開。

感謝

+3

一個快速點:string.length減不會給你使用,除非你已經設置編碼簡單的ASCII字節數。 –

+0

好找@CodeCaster。看起來像是重複的。 –

+0

@DavidArno - 感謝您指出大衛。我只是將我的源代碼更改爲'返回System.Text.Encoding.UTF8.GetByteCount(recordField.GetValue(dataRecord,null).ToString());'。 – UberNubIsTrue

回答

2

兩個可能的解決方案:

  1. Marshal.SizeOf()方法(http://msdn.microsoft.com/en-us/library/y3ybkfb3.aspx

  2. 的關鍵字的sizeof(http://msdn.microsoft.com/en-us/library/eahchzkf%28VS.71%29.aspx

的後者雖然仍然需要一個開關h聲明,因爲這是不可能的:

int x; 
sizeof(x); 

sizeof只適用於明確聲明的類型,例如, sizeof(int)

所以在這種情況下(1)是更好的選擇(它適用於所有類型,不僅適用於switch語句中的那些類型)。

+0

謝謝大衛。我使用了選項1,它完美地工作。我也很欣賞關於編碼問題的反饋。我學到了很多,這是一個很大的幫助! – UberNubIsTrue

+1

重要的是要注意,這兩種方法不一定會返回相同的值。 'sizeof'返回受管理的大小,Marshal.SizeOf是p/invoke編組使用的大小。 – CodesInChaos

+0

@CodesInChaos - 感謝您指出這一點。我需要了解更多關於編組以確定是否/如何對我的項目產生影響。 – UberNubIsTrue

3

這可能有助於

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; 
} 

}

+0

這仍然會給字符串輸入錯誤的值。 –

+0

謝謝穆罕默德。隨着我爲獲得UTF-8字節計數所做的更改(基於David的評論),此解決方案完美無缺。 – UberNubIsTrue

相關問題