繁体   English   中英

无法转换'System.Reflection.RuntimePropertyInfo'类型的对象

[英]Unable to cast object of type 'System.Reflection.RuntimePropertyInfo'

我有图书馆和控制台程序。 该程序动态加载库。 在库中存在字节数组。 我尝试得到这个数组。 在计划中:

MemberInfo[] ByteArrayFile = HtmlPackage.GetMember("HtmlFile");
FieldInfo field;
try
{
   field = (FieldInfo)ByteArrayFile[0];//throw exception here
}
catch (Exception e)
{
  String err = e.ToString();
  throw e;
}
byte[] HtmlFileArray = (byte[])field.GetValue(htmlPackage);

此错误抛出异常:

“System.InvalidCastException:无法将'System.Reflection.RuntimePropertyInfo'类型的对象强制转换为'System.Reflection.FieldInfo'。\\ r \\ n at ...

那它是如何修复的?

Fields( FieldInfo )和属性( PropertyInfo )不共享API - 因此您需要解决它:

MemberInfo member = ByteArrayFile[0];
byte[] HtmlFileArray;
switch (member.MemberType)
{
    case MemberTypes.Field:
        HtmlFileArray = (byte[])(((FieldInfo)member).GetValue(htmlPackage));
        break;
    case MemberTypes.Property:
        HtmlFileArray = (byte[])(((PropertyInfo)member).GetValue(htmlPackage));
        break;
    default:
        throw new NotSupportedException(member.MemberType.ToString());
}

但是,这容易(并且更有效(由于策略缓存),而不会引入任何其他弱点):

byte[] HtmlFileArray = ((dynamic)htmlPackage).HtmlFile;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM