2010-04-15 6 views
3

기본 속성 설정 : 내가 객체에 전달하고이 방법은 재귀 적으로 자식 개체와 개체를 인스턴스화 곳 C#을 재귀 ​​반사 및 일반 목록 나는 다음과 같은 달성하기 위해 반사를 사용하려고

내가하는 방법이 필요하고 기본 값으로 등록 정보를 설정하십시오. 필요에 따라 여러 수준으로 인스턴스화 된 전체 개체가 필요합니다.

이 메서드는 다른 개체의 일반 목록이 될 여러 속성을 가진 개체를 처리 할 수 ​​있어야합니다.

private void SetPropertyValues(object obj) 
{ 
    PropertyInfo[] properties = obj.GetType().GetProperties(); 

    foreach (PropertyInfo property in properties) 
    { 
     if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects")) 
     { 
      Type propType = property.PropertyType; 

      var subObject = Activator.CreateInstance(propType); 
      SetPropertyValues(subObject); 
      property.SetValue(obj, subObject, null); 
     } 
     else if (property.PropertyType == typeof(string)) 
     { 
      property.SetValue(obj, property.Name, null); 
     } 
     else if (property.PropertyType == typeof(DateTime)) 
     { 
      property.SetValue(obj, DateTime.Today, null); 
     } 
     else if (property.PropertyType == typeof(int)) 
     { 
      property.SetValue(obj, 0, null); 
     } 
     else if (property.PropertyType == typeof(decimal)) 
     { 
      property.SetValue(obj, 0, null); 
     } 
    } 
} 

감사

+0

오류가 발생한 행을 확인하는 것이 도움이됩니다. 또한 형식 이름에 BusinessObjects가 포함 된 속성에 대해서만 새 개체를 만드는 것처럼 보입니다.이 속성이 사용자의 의도인지 확실하지 않습니다. –

답변

0

이 까다로운 일 :

입니다 : 여기

내 샘플 코드 (나는 List<AnotherSetObjects>을 포함하는 객체를 얻을 때이 매개 변수 카운트 불일치 예외를 얻고있다 일부 "BusinessObjects"유형의 일반 목록을 속성으로 포함하는 이니셜 라이저를 전달하면이 속성은 다음을 전달합니다.

if (property.PropertyType.IsClass && property.PropertyType != typeof(string) && property.PropertyType.FullName.Contains("BusinessObjects"))

표현, 인스턴스화 된 제네릭 형식이 같은 이름을 가지고 있기 때문에 :

이것은 초기화 방법 결과
System.Collections.Generic.List`1[[ConsoleApplication92.XXXBusinessObjects, ConsoleApplication92, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] 

가 매개 변수로 목록 자체 호출되고 있습니다. 이 목록에는 SomeBusinessObjects 유형의 Item이라는 인덱서가 있습니다. 이것 역시 위의 조건을 통과하므로 초기화 할 수도 있습니다.

obj.ListProperty.Item = new SomeBusinessObject(); 

실제로, 당신은 매개 변수를 누락되었습니다 인덱서 만이

obj.ListProperty[0] = new SomeBusinessObject(); 

이 보여처럼 초기화에 사용될 수있는 반면 : 결과이 같은 것입니다.

당신이 거 이것에 대해 할 것은 당신에게 달려있다 :)

+0

내 대답보기. :) – Nayan

1

당신은 일반적인 컨테이너 마찬가지입니다 property.PropertyType.IsGeneric를 확인하여 필터링 할 수 있습니다. 필요한 경우 property.PropertyType.IsArray도 확인하십시오.

또한 제네릭 이외의 컨테이너를 피할 수도 있습니다. 이 경우 해당 컨테이너의 인터페이스 유형으로 될 객체를 테스트하십시오. 예 : IList.

bool isList(object data) 
{ 
    System.Collections.IList list = data as System.Collections.IList; 
    return list != null; 
} 

... 
if (isList(obj)) { 
    //do stuff that take special care of object which is a List 
    //It will be true for generic type lists too! 
} 
+2

아니면 그냥이 정확한 목적을 위해 존재하는 언어의 "is"연산자를 사용할 수 있으며 불필요한 메서드 호출과 동등 비교를 피할 수 있습니다. –

관련 문제