Mar*_*kus 2 c# arrays reflection propertyinfo
我正在尝试使用反射获取 Byte[] 。不幸的是结果总是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;
}
Run Code Online (Sandbox Code Playgroud)
这是工作代码:
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[];
}
}
}
Run Code Online (Sandbox Code Playgroud)
你的代码看起来很奇怪。您正在创建该参数类型的新实例,并尝试从该实例获取值。您应该使用参数本身:
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[];
}
}
}
Run Code Online (Sandbox Code Playgroud)
顺便提一句:
return true
在返回的方法中void
是非法的,并且会导致编译器错误。在您的情况下不需要使用反射。你可以简单地这样写:
public static void SaveFile(BusinessObject document)
{
Byte[] content = document.Content;
// do something with content.
}
Run Code Online (Sandbox Code Playgroud)
Content
仅当在派生类上定义BusinessObject
且不仅仅在派生类上定义时,这才是正确的。