c# - Unable to cast object of type 'System.Reflection.RuntimePropertyInfo' -


i have library , console program. program dynamically load library. in library exist byte array. try array. in program:

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); 

this error throw exception:

"system.invalidcastexception: unable cast object of type 'system.reflection.runtimepropertyinfo' type 'system.reflection.fieldinfo'.\r\n @ ...

so how it's fixed?

fields (fieldinfo) , properties (propertyinfo) not share api - need work around it:

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()); } 

however, much easier (and more efficient (due strategy caching), without introducing additional weaknesses):

byte[] htmlfilearray = ((dynamic)htmlpackage).htmlfile; 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -