我有两个课程'菜单'和'用餐'。菜单需要根据运行时的路径创建膳食实例。例如,我有路径,如
C:\Users\devmachine\Documents\Visual Studio 2017\Projects\MealsLibrary\MealsLibrary\Meals.cs
菜单类位于不同的解决方案中,也位于不同的硬盘位置。
所以,我正在尝试使用Reflection.Assembly.LoadFrom,但我还没有成功,它告诉我需要一个程序集清单。
那么,如何创建一个单独的解决方案中的类的实例?
答案 0 :(得分:1)
要从ClassB
AssemblyB
中AssemblyA
实例化AssemblyB
,其中Assembly.LoadNnn
NOT 引用的程序集(但加载Assembly.LoadNnn
1}}您可以执行以下操作:
DefinedTypes
重载之一Activator.CreateInstanceNnn
以检测类型 using System;
using System.Reflection;
using System.Diagnostics.Contracts;
// this is AssemblyB
// residing at C:\TEMP\AssemblyB.dll
namespace Com.Example.SO12188029.AssemblyB
{
public class ClassB
{
public string Property { get; set; } = "tralala";
}
}
// this is AssemblyA
// residing at C:\SomeWhereElse\AssemblyA.dll
namespace Com.Example.SO12188029.AssemblyA
{
public class ClassA
{
private const string assemblyBPathAndFileName = @"C:\TEMP\AssemblyB.dll";
private const string typeFromAssemblyBToBeInstantiated = @"Com.Example.SO12188029.AssemblyB.ClassB";
public static void Main(string[] args)
{
// try to load assembly
var assembly = Assembly.LoadFrom(assemblyBPathAndFileName);
Contract.Assert(null != assembly, assemblyBPathAndFileName);
// make sure type exists in assembly
var type = assembly.DefinedTypes.First(e => e.IsClass && !e.IsAbstract
&& e.FullName == typeFromAssemblyBToBeInstantiated);
Contract.Assert(null != type, typeFromAssemblyBToBeInstantiated);
// try to get instance of type
var instance = Activator.CreateInstance(assembly.ManifestModule.FullyQualifiedName, typeFromAssemblyBToBeInstantiated);
// ... now we have an instance, but as long as you do not know what *kind* of instance this is
// you cannot do much with it, unless - we use reflection to get access to the instance
var propertyInfo = instance.GetType().GetProperty("Property");
var propertyValue = propertyInfo.GetValue(instance);
Console.WriteLine("ClassB.PropertyValue '{0}'", propertyValue);
}
}
}
实例化类型以下是一些适合您的代码:
ClassB
但是,这实际上非常不方便使用,因此您最好使用两个程序集共有的接口。有了这个,你可以将IClassB
投射到例如{1}}。 Activator
并访问其属性而不会回退到反射。而不是使用Assembly.LoadFrom
和Activator.CreateInstanceFrom
我会考虑使用StructureMap
,以便您可以扫描程序集并从中获取实例(尽管它可能被视为AntiPattern,但不会造成更多伤害比#facebook-icon
本身。