필자는 재귀 적으로 클래스의 모든 속성을 통과해야하며 속성이 문자열 일 경우 사용자 지정 논리를 수행해야합니다. 재귀 라인에 넣어야 할 것을 조언 해주세요.C에서 속성 정보에서 참조를 얻는 방법 #
void ProcessAllStrings<T>(ref T objToRip)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Type typeParameterType = typeof (T);
foreach (PropertyInfo p in typeParameterType.GetProperties(flags))
{
Type currentNodeType = p.PropertyType;
if (currentNodeType == typeof (String))
{
//here I do my custom string handling. Code deleted
}
//if non primitive and non string then recurse. (nested/inner class instances)
// see http://stackoverflow.com/questions/4444908/detecting-native-objects-with-reflection
else if (currentNodeType != typeof (object) && Type.GetTypeCode(currentNodeType) == TypeCode.Object)
{
//I need to get the reference to this property which happens to be a nested class
//but propertyInfo only provides GetValue(). No GetReference available..
ProcessAllStrings(ref "dont know what to put here");
}
}
}
'ref' 또는 generics'T'를 사용하는 특별한 이유는 무엇입니까? 아마도'typeParameterType'은'objToRip' 대신에 메소드에 대한 입력 매개 변수 여야합니다. EDIT : 무한 재귀로 실행되는 것을 조심해야 할 수도 있습니다 : 사용자 정의 유형이 자신의 인스턴스를 (또는 속성을 따라 체인이 그렇다면) 계속 반복해서 실행하고 싶지는 않습니다. –
모든 답글에 대해 thx. 매우 도움이됩니다. 내 요구 사항은 xsd.exe에 의해 생성 된 많은 xml 클래스를 통과하고 xml 클래스의 모든 문자열 노드로 일부 사용자 지정 논리를 수행하는 것입니다. 그러므로은 일반적인 사용자 생성 클래스 일 수 있기 때문에. –
Gullu