을 구현하는 다른 클래스를 찾고있는 속성을 탐색하고 생성하는 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);
}
(HTTP [타입에서 새 개체 인스턴스를 가져옵니다]의 가능한 중복 : // –