2013-10-03 130 views
2

我试图编写一个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); 
    } 
+0

的[从一个类型的新对象实例(HTTP可能重复:// stackoverflow.com/questions/752/get-a-new-object-instance-from-a-type) –

回答

5

您可以创建一个非泛型方法,并使用它:

public static T Create<T>() where T : ICreateEmptyInstance, new() 
{ 
    return (T) Create(typeof (T)); 
} 

private static object Create(Type type) 
{ 
    var instance = Activator.CreateInstance(type); 

    var properties = type.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; 
} 
+0

这看起来不错,但我得到了堆栈溢出异常!循环创建了我认为是错误的类型,现在要测试这一点。 – CaffGeek

+0

对不起,我封了。 –

+0

收藏呢?关于如何确保实例具有使用空列表创建的列表属性的任何想法? – CaffGeek