在C#中创建一个位于单独项目中的类的实例

时间:2017-03-14 18:05:38

标签: c# visual-studio reflection .net-assembly

我有两个课程'菜单'和'用餐'。菜单需要根据运行时的路径创建膳食实例。例如,我有路径,如 C:\Users\devmachine\Documents\Visual Studio 2017\Projects\MealsLibrary\MealsLibrary\Meals.cs

菜单类位于不同的解决方案中,也位于不同的硬盘位置。

所以,我正在尝试使用Reflection.Assembly.LoadFrom,但我还没有成功,它告诉我需要一个程序集清单。

那么,如何创建一个单独的解决方案中的类的实例?

1 个答案:

答案 0 :(得分:1)

要从ClassB AssemblyBAssemblyA实例化AssemblyB,其中Assembly.LoadNnn NOT 引用的程序集(但加载Assembly.LoadNnn 1}}您可以执行以下操作:

  1. 通过DefinedTypes重载之一
  2. 加载程序集
  3. 扫描已加载装配的Activator.CreateInstanceNnn以检测类型
  4. 使用 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); } } } 实例化类型
  5. 以下是一些适合您的代码:

    ClassB

    但是,这实际上非常不方便使用,因此您最好使用两个程序集共有的接口。有了这个,你可以将IClassB投射到例如{1}}。 Activator并访问其属性而不会回退到反射。而不是使用Assembly.LoadFromActivator.CreateInstanceFrom我会考虑使用StructureMap,以便您可以扫描程序集并从中获取实例(尽管它可能被视为AntiPattern,但不会造成更多伤害比#facebook-icon本身。

相关问题