简体   繁体   中英

Can't cast object to its own type

In a Blazor page, I've got this weird bug when "casting" a model to it's actual given type. The error is this:

Unable to set property 'Model' on object of type 'CSBApp.ExtHdr'. 
The error was: [A]TQ.ModelExt cannot be cast to [B]TQ.ModelExt. 
Type A originates from 'TQ.Exts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' 
at location 'C:\_work\Server.SSB\bin\Debug\net5.0-windows\TQ.Exts.dll'. 
Type B originates from 'TQ.Exts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' 
at location 'C:\_work\Server.SSB\bin\Debug\net5.0-windows\TQ.Exts.dll'.

Seems like there are two identical assemblies loaded!

object Model = ...; // actually a ModelExt
var a1 = Model.GetType().Assembly;
var a2 = typeof(ModelExt).Assembly;
if (a1 != a2) {
    DBG.Log("merde...");
}

The assemblies, a1 & a2, have the same name, version & location but different m_assembly.

How is this possible??

Answering my own question. See here ( https://docs.microsoft.com/en-us/dotnet/framework/deployment/best-practices-for-assembly-loading ) about loading in multiple contexts.

In short, Use Assembly.LoadFrom() instead of Assembly.LoadFile() .

And thanks to Jeremy Lakeman for the AppDomain.AssemblyLoad event idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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