【发布时间】:2018-09-04 16:48:18
【问题描述】:
长期以来,我一直在努力寻找一种方法来动态实例化所有扩展特定基类的类(在运行时)。根据我的阅读,它应该使用Reflection 来完成,不幸的是我还没有弄清楚如何。
我的项目结构如下:
Library
--|
|
--Vehicle.cs (abstract class)
|
--Car.cs (extending vehicle)
|
--Bike.cs (extending vehicle)
|
--Scooter.cs (extending vehicle)
|
--InstanceService.cs (static class)
|
|
ConsoleApplication
--|
|
--Program.cs
InstanceService 类包含一个通用方法,该方法应该返回一个IEnumerable<T>,其中包含扩展Vehicle 的实例化类,即Car, Bike & Scooter。
下面发布的代码是 InstanceService 类的当前状态,在尝试了大量不同的解决方案之后,这意味着它主要包含用于调试的工具。
InstanceService.cs
using System;
using System.Collections.Generic;
namespace Library
{
public static class InstanceService<T>
{
//returns instances of all classes of type T
public static IEnumerable<T> GetInstances()
{
var interfaceType = typeof(T);
List<T> list = new List<T>();
Console.WriteLine("Interface type: " + interfaceType.ToString());
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach(var assembly in assemblies)
{
Console.WriteLine("Assembly: " + assembly.ToString());
if (assembly.GetType().IsAbstract)
{
var instance = (T) Activator.CreateInstance(assembly.GetType());
list.Add(instance);
}
}
return list;
}
}
}
我还附上了抽象 Vehicle 类的代码以及它的实现之一。
Vehicle.cs
namespace Library
{
public abstract class Vehicle
{
protected float maxSpeedInKmPerHour;
protected float weightInKg;
protected float priceInDkk;
}
}
Car.cs
namespace Library
{
public class Car : Vehicle
{
public Car()
{
this.maxSpeedInKmPerHour = 1200;
this.weightInKg = 45000;
this.priceInDkk = 71000000;
}
}
}
【问题讨论】:
-
目前的方法(具体而言)出了什么问题?
-
没什么特别的,至少它没有返回任何错误。我只是好奇如何以最好的方式实现这一点。此外,使用当前方法,该函数似乎只返回一个无法循环的对象,而实际上它应该返回一个包含 3 个从
Vehicle派生的实例化类的列表。然后我在函数返回的列表上使用ToString(),得到如下输出System.Collections.Generic.List1[Library.Vehicle]
标签: c# .net reflection system.reflection decoupling