很长一段时间以来,我一直在努力寻找一种方法来动态实例化扩展特定基类的所有类(在运行时)。根据我的阅读,它应该使用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
。
在尝试了大量不同的解决方案之后,下面列出的代码是Instance Service类的当前状态,这意味着它主要包含用于调试的工具。
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;
}
}
}
我认为你应该感兴趣的方法是IsAssignableFrom
。
另外,使用LINQ代码要容易得多,如果你允许使用它,并且因为你一次创建一个对象,我建议使用yield return
。
static IEnumerable<T> GetInstances<T>()
{
var baseType = typeof(T);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany( a => a.GetTypes() )
.Where
(
t => baseType.IsAssignableFrom(t) //Derives from base
&& !t.IsAbstract //Is not abstract
&& (t.GetConstructor(Type.EmptyTypes) != null) //Has default constructor
);
foreach (var t in types)
{
yield return (T)Activator.CreateInstance(t);
}
}
或者,如果由于某种原因你正在炫耀,你想用一个声明来做:
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany( a => a.GetTypes() )
.Where
(
t => typeof(T)IsAssignableFrom(t)
&& !t.IsAbstract
&& (t.GetConstructor(Type.EmptyTypes) != null)
)
.Select
(
t => (T)Activator.CreateInstance(t)
);
这适用于任何可以使用默认构造函数实例化的类型。除了我遗漏的东西之外,你的类派生自另一个类的事实是不重要的。
private T MakeInstance<T>()
{
// the empty Type[] means you are passing nothing to the constructor - which gives
// you the default constructor. If you need to pass in an int to instantiate it, you
// could add int to the Type[]...
ConstructorInfo defaultCtor = typeof(T).GetConstructor(new Type[] { });
// if there is no default constructor, then it will be null, so you must check
if (defaultCtor == null)
throw new Exception("No default constructor");
else
{
T instance = (T)defaultCtor.Invoke(new object[] { }); // again, nothing to pass in. If the constructor needs anything, include it here.
return instance;
}
}