2012-04-30 7 views
2

응용 프로그램의 경우 런타임 정의 된 메서드의 매개 변수가 어떻게 보이는지 보여주는 템플릿을 표시하려고합니다. 필자가 작업하고있는 테스트 케이스는 "PERSON = (FIRST = first; LAST = last);"을 표시해야하며, Person이라는 이름의 매개 변수에는 Name 유형이 있고 Name에는 First와 Last의 두 가지 속성이 있습니다. 대신 다음 코드는 "PERSON =();"을 표시합니다.ParameterInfo에서 중첩 된 모든 유형 가져 오기

GetNestedTypes는 아무 것도 반환하지 않습니다. 그 이유는 무엇입니까?

public static string GetParameterTemplate(MethodInfo method) 
{ 
    StringBuilder output = new StringBuilder(); 
    foreach (ParameterInfo pi in method.GetParameters()) 
    { 
     output.Append(parameterTemplateHelper(pi.Name, pi.ParameterType)); 
    } 
    return output.ToString(); 
} 

private static string parameterTemplateHelper(string pName, Type pType) 
{ 
    string key = pName.ToUpper(); 
    string value = ""; 

    if (pType.IsPrimitive) 
    { 
     // it's a primitive 
     value = pName.ToLower(); 
    } 
    else if (pType.IsArray) 
    { 
     if (pType.GetElementType().IsPrimitive) 
     { 
      // array of primitives 
      value = String.Format("{0}1, {0}2;", pName.ToLower()); 
     } 
     else 
     { 
      // array of objects 
      StringBuilder sb = new StringBuilder(); 
      foreach (Type t in pType.GetElementType().GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic)) 
      { 
       sb.Append(parameterTemplateHelper(t.Name, t)); 
      } 
      value = String.Format("({0}), ({0});", sb); 
     } 
    } 
    else 
    { 
     // object 
     StringBuilder sb = new StringBuilder(); 
     Type[] junk = pType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic); 
     foreach (Type t in pType.GetNestedTypes()) 
     { 
      sb.Append(parameterTemplateHelper(t.Name, t)); 
     } 
     value = String.Format("({0});", sb.ToString()); 
    } 

    string output = key + " = " + value.ToString(); 
    return output; 
} 

답변

2

코드는 중첩 된 유형을 찾고있다 - 즉, 다른 유형의 Person 내에서 선언. 이는 속성 인Person 내에 찾는 것과 동일하지 않습니다.

여기에 중첩 된 유형의 클래스입니다 :

public class Name 
{ 
    public class Nested1 {} 
    public class Nested2 {} 
} 

은 다음 특성을 가진 클래스의 :

public class Name 
{ 
    public string Name { get; set; } 
    public string Name { get; set; } 
} 

내 생각 엔 당신의 상황이 훨씬 더 처음보다 두 번째 같은 점이다 ... Type.GetNestedTypes 대신 Type.GetProperties을 사용하십시오.

+1

내 이마에는 빨간색의 손 모양의 자국이 있습니다. 그 점을 지적 해 주셔서 감사합니다. – user1269310