Caf*_*eek 2 c# reflection null-object-pattern
我正在尝试编写一个NullObject创建方法,在其中传入一个实现ICreateEmptyInstance接口(即为空)的类名,并且它遍历它的属性,寻找实现的其他类,ICreateEmptyInstance并将创建那些的"Null"实例.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我应该可以用它来称呼它
var myEmptyClass = NullObject.Create<MyClass>();
Run Code Online (Sandbox Code Playgroud)
我遇到问题的地方是在foreach循环中,有了这一行
var propertyInstance = NullObject.Create<property.PropertyType>();
Run Code Online (Sandbox Code Playgroud)
...显然这不起作用,但我怎样才能完成创建"空对象"以分配给我正在创建的实例.
编辑:那么泛型呢?我想创建空实例
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);
}
Run Code Online (Sandbox Code Playgroud)
您可以创建非泛型方法并使用它:
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;
}
Run Code Online (Sandbox Code Playgroud)