2012-10-10 64 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) 
相关问题