gpt4 book ai didi

c# - 无法转换类型为 'System.Reflection.RuntimePropertyInfo' 的对象

转载 作者:行者123 更新时间:2023-11-30 16:59:52 28 4
gpt4 key购买 nike

我有库和控制台程序。程序动态加载库。库中存在字节数组。我试着得到这个数组。在程序中:

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: Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' to type 'System.Reflection.FieldInfo'.\r\n at ...

那么它是如何修复的呢?

最佳答案

字段 (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;

关于c# - 无法转换类型为 'System.Reflection.RuntimePropertyInfo' 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23056833/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com