C# 在C中创建独立项目中的类的实例#
我有两门课“菜单”和“膳食”。菜单需要根据运行时的路径创建一个膳食实例。例如,我有如下路径C# 在C中创建独立项目中的类的实例#,c#,visual-studio,reflection,.net-assembly,C#,Visual Studio,Reflection,.net Assembly,我有两门课“菜单”和“膳食”。菜单需要根据运行时的路径创建一个膳食实例。例如,我有如下路径 C:\Users\devmachine\Documents\Visual Studio 2017\Projects\MealsLibrary\MealsLibrary\founds.cs 菜单类位于不同的解决方案中,也位于不同的硬盘驱动器位置 到目前为止,我正在尝试使用Reflection.Assembly.LoadFrom,但我没有成功,因为它告诉我需要一个程序集清单 那么,如何在单独的解决方案中创建类
C:\Users\devmachine\Documents\Visual Studio 2017\Projects\MealsLibrary\MealsLibrary\founds.cs
菜单类位于不同的解决方案中,也位于不同的硬盘驱动器位置
到目前为止,我正在尝试使用Reflection.Assembly.LoadFrom,但我没有成功,因为它告诉我需要一个程序集清单
那么,如何在单独的解决方案中创建类的实例呢?为了从
AssemblyA
中实例化ClassB
内部AssemblyB
,其中AssemblyB
不是引用的程序集(但加载了assembly.loadnn
,您可以执行以下操作:
Assembly.LoadNnn
重载之一加载程序集定义类型
,以检测类型Activator.createInstanceNN
实例化类型 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 <代码>转换成例如<代码> ICLASB并访问它的属性而不退回到反射。而不是使用,我会考虑使用,这样你就可以扫描你的程序集并得到一个n实例(虽然它可能被视为反模式,但不会比
Activator
本身造成更大的危害).我的工作中可能重复的要求是,该类一直在更改,因此不值得将其添加为引用。如果更改的类位于您管理的另一个解决方案或项目中,您肯定需要引用。当您更改该类时,将自动重新生成引用该类的程序集当他们构建“独立解决方案”时获取最新的.dll=两个独立的团队维护自己的程序集,您需要进行互操作?然后,两个团队应该就一个不会一直更改的接口达成一致,您可以编写该接口的模拟实现,以开发和测试该接口,并在生产中使用运行时绑定。我已经向我们的软件团队提出了相同的声明您是架构师,但这就是他希望我编写此应用程序的方式。没有引用,都是在运行时编写的。