2013-10-03 5 views
2

을 구현하는 다른 클래스를 찾고있는 속성을 탐색하고 생성하는 ICreateEmptyInstance 인터페이스를 구현하는 클래스 이름을 전달하는 NullObject 작성 메소드를 작성하려고합니다. "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; 
    } 
} 

나는 분명히 ...이 줄

var propertyInstance = NullObject.Create<property.PropertyType>(); 

로, 내가 문제에 봉착하면 foreach 루프의 내부에이

var myEmptyClass = NullObject.Create<MyClass>(); 

로 전화를 할 수 있어야한다 그게 작동하지 않지만, 어떻게 내가 현재 만들고있는 인스턴스에 할당 할 "null 개체"를 만들 수 있습니다.

편집 : 그리고 generics는 어떻습니까 ?? 내가 좋아하는 것 빈 인스턴스가

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 [타입에서 새 개체 인스턴스를 가져옵니다]의 가능한 중복 : // –

답변

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

관련 문제