Getting byte[] from PropertyInfo returns NULL
-
06-07-2021 - |
문제
I'm trying to get a Byte[] using reflection. Unfortunately the result it always NULL. The property is filled with data. Here's my code snippet.
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;
}
Here's the working code:
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[];
}
}
}
해결책
Your code looks strange. You are creating a new instance of the type of the parameter and try to get the value from that instance. You should be using the parameter itself instead:
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:
return true
in a method that returnsvoid
is illegal and will lead to a compiler error.There is no need to use reflection in your case. You could simply write this:
public static void SaveFile(BusinessObject document) { Byte[] content = document.Content; // do something with content. }
This is only true if
Content
is defined onBusinessObject
and not only on derived classes.
다른 팁
from your code snippet it appears you are not populating any value.
Object obj = Activator.CreateInstance(boType);
this would just invoke the default consturctor and assign default values for all types. and for byte[] it is null
it should be
item.GetValue(document, null)
제휴하지 않습니다 StackOverflow