很长时间以来,我一直在努力寻找一种方法来动态实例化扩展特定基类的所有类(在运行时)。根据我的阅读,应该使用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;
}
}
}
答案 0 :(得分:1)
我认为您应该感兴趣的方法是IsAssignableFrom
。
此外,如果允许使用LINQ,则使用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)
);
答案 1 :(得分:0)
这适用于可以使用默认构造函数实例化的任何类型。除非我遗漏了一些东西,否则您的类是从另一个类派生的事实就不重要了。
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;
}
}