2012-10-10 62 views
1

我想要使用反射得到一個字節[]。不幸的是,結果總是空的。該物業充滿了數據。這是我的代碼片段。從PropertyInfo獲取字節[]返回NULL

public static void SaveFile(BusinessObject document) 
{ 
    Type boType = document.GetType(); 
    PropertyInfo[] propertyInfo = boType.GetProperties(); 
    Object obj = Activator.CreateInstance(boType); 
    foreach (PropertyInfo item in propertyInfo) 
    { 
     Type xy = item.PropertyType; 
     if (String.Equals(item.Name, "Content") && (item.PropertyType == typeof(Byte[]))) 
     { 
      Byte[] content = item.GetValue(obj, null) as Byte[]; 
     } 
    } 
    return true; 
} 

這裏的工作代碼:

public static void SaveFile(BusinessObject document) 
{ 
    Type boType = document.GetType(); 
    PropertyInfo[] propertyInfo = boType.GetProperties(); 
    foreach (PropertyInfo item in propertyInfo) 
    { 
     if (String.Equals(item.Name, "Content") && (item.PropertyType == typeof(Byte[]))) 
     { 
      Byte[] content = item.GetValue(document, null) as Byte[]; 
     } 
    } 
} 

回答

4

您的代碼看起來很奇怪。您正在創建參數類型的實例,並嘗試從該實例獲取值。你應該使用參數本身,而不是:

public static void SaveFile(BusinessObject document) 
{ 
    Type boType = document.GetType(); 
    PropertyInfo[] propertyInfo = boType.GetProperties(); 
    foreach (PropertyInfo item in propertyInfo) 
    { 
     Type xy = item.PropertyType; 
     if (String.Equals(item.Name, "Content") && 
      (item.PropertyType == typeof(Byte[]))) 
     { 
      Byte[] content = item.GetValue(document, null) as Byte[]; 
     } 
    } 
} 

BTW:

  1. return true在返回void是非法的,將導致一個編譯器錯誤的方法。
  2. 你的情況沒有必要使用反射。你可以簡單地寫:

    public static void SaveFile(BusinessObject document) 
    { 
        Byte[] content = document.Content; 
        // do something with content. 
    } 
    

    這是唯一真正的,如果ContentBusinessObject定義,不僅對派生類。

+0

回覆BTW 2:可能的內容僅在一個派生類的屬性。 –

+0

@亨克·霍特曼:是的,情況可能如此。 –

+0

嗨,丹尼爾。當然你是對的。我怎麼會這麼盲目。謝謝! – Markus

1

從你的代碼片段看來你沒有填充任何值。

Object obj = Activator.CreateInstance(boType); 

這隻會調用默認的構造函數併爲所有類型分配默認值。 以及用於字節[]它是

它應該是

item.GetValue(document, null) 
相關問題