我试图编写一个NullObject
创建方法,其中我传入一个实现了ICreateEmptyInstance
接口(即空)的类名称,并引导其属性查找实现ICreateEmptyInstance
的其他类,并将创建这些的“空”实例。使用反射创建对象
public interface ICreateEmptyInstance { }
public static class NullObject
{
public static T Create<T>() where T : ICreateEmptyInstance, new()
{
var instance = new T();
var properties = typeof(T).GetProperties();
foreach (var property in properties.Where(property => typeof(ICreateEmptyInstance).IsAssignableFrom(property.PropertyType)))
{
var propertyInstance = NullObject.Create<property.PropertyType>();
property.SetValue(instance, propertyInstance);
}
return instance;
}
}
我应该能够与此
var myEmptyClass = NullObject.Create<MyClass>();
如果我有问题是foreach循环的内部称呼它,这条线
var propertyInstance = NullObject.Create<property.PropertyType>();
...明显这不起作用,但我怎样才能完成创建一个“空对象”分配给我目前创建的实例。编辑: 那么泛型呢?我想空的情况下创建
foreach (var property in properties.Where(property => property.GetType().IsGenericType))
{
var propertyInstance = Enumerable.Empty<>(); //TODO: how do I get the type for here?
property.SetValue(instance, propertyInstance);
}
的[从一个类型的新对象实例(HTTP可能重复:// stackoverflow.com/questions/752/get-a-new-object-instance-from-a-type) –