我正在用.NET-5编写C#,并尝试基于一些XML实例化一个类。这似乎工作得很好,因为我得到了所需对象的一个实例:
var refxmlFileInfo = new FileInfo(settings.COBDateSetting);
// Casting fails. The Object is of the expected type
CalcConfiguration.CobDateSettings = (COBDate_Settings)factoryHelper.GetInstance(refxmlFileInfo, xmlFileInfo.FullName);但是,转换失败,并出现一个奇怪的错误,表明实例和目标的类型相同:
[A]DataModel.BusinessDays.COBDate_Settings cannot be cast to
[B]DataModel.BusinessDays.COBDate_Settings.
Type A originates from 'DataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location
'<REMOVED>\bin\Debug\net5.0\DataModel.dll'.
Type B originates from 'DataModel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location
'<REMOVED>\bin\Debug\net5.0\DataModel.dll'.我已经检查了项目之间的引用,但没有发现任何异常。
public object GetInstance(FileInfo xmlFileInfo,string usedWhere)
{
ISettings setting = GetSettings(xmlFileInfo, usedWhere);
var classToResolve = ((IDefiningType)setting).GetDefiningType();
var classInstance = (IInitializeXML)Unity.Resolve(classToResolve);
classInstance.InitializeXML(this, xmlFileInfo);
return classInstance;
}
public ISettings GetSettings(FileInfo xmlFileInfo,string usedWhere)
{
if (!xmlFileInfo.Exists)
{
var msg = string.Format("Path: <{0}> not found in referenced file: {1}", xmlFileInfo.FullName,usedWhere);
throw new Exception(msg);
}
// Uses some regex to find out which class is XML-Serialized. The string is // then checked against all types in assembly. Types are extracted using
// *.dll and the loading the assembly
var typeToResolve = GetSettingsType(xmlFileInfo);
// We now have a instance of the definingType class
ISettings setting = (ISettings)Convert.ChangeType(SettingsSerializer.Deserialize(typeToResolve, xmlFileInfo), typeToResolve);
return setting;
}有没有人知道问题出在哪里?
发布于 2021-06-09 15:04:24
我找到了解决方案。原因是我使用LoadFile遍历了DLL:
var baseDir = AppContext.BaseDirectory;
var dir = new DirectoryInfo(baseDir);
foreach (var dllfile in dir.GetFiles("*.dll"))似乎C#没有意识到这些类是相同的,并且它们来自同一个动态链接库。我使用这篇文章中的一个解决方案解决了这个问题:
Getting Information about a assembly which is present in Solution
public IEnumerable<Assembly> GetAssemblies()
{
var list = new List<string>();
var stack = new Stack<Assembly>();
stack.Push(Assembly.GetEntryAssembly());
do
{
var asm = stack.Pop();
yield return asm;
foreach (var reference in asm.GetReferencedAssemblies())
if (!list.Contains(reference.FullName))
{
stack.Push(Assembly.Load(reference));
list.Add(reference.FullName);
}
}
while (stack.Count > 0);
}但是,在这种情况下,我必须引用所有程序集,并在引用的程序集中调用某些内容。上面的代码似乎只有在dlls已经加载的情况下才能工作。
https://stackoverflow.com/questions/67887729
复制相似问题