Код: Выделить всё
void someCode()
{
Nest MyNest = new Nest();
createInstancesOfAllClassesInside(MyNest);
}
void createInstancesOfAllClassesInside(object anyObj)
{
//How, using reflection ?
}
public class Nest
{
public class A
{
public class A1
{
public class A2
{
public string x = "Activate me!";
}
}
}
public class B
{
public class B1
{
}
}
public string s = "Hello";
}
Я добавлю свою (нерабочую) попытку далеко, чтобы проблема стала понятнее:
Код: Выделить всё
public void CreateInstancesOfAllClassesInside(object obj)
{
var objType = obj.GetType();
// Loop through all nested types inside the object's type
foreach (Type nestedType in objType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))
{
// Create an instance of the nested type
var instance = Activator.CreateInstance(nestedType);
// cant find something like: SetValue(obj, instance) to attach the object to its container !
// Recursively call the function to instantiate nested classes inside this instance
CreateInstancesOfAllClassesInside(instance);
}
}
public void CreateInstancesOfAllClassesInside2(ref object obj)
{
var objType = obj.GetType();
// Loop through all nested types inside the object's type
foreach (Type nestedType in objType.GetNestedTypes(BindingFlags.Public | BindingFlags.NonPublic))
{
// Create an instance of the nested type using its constructor
var instance = Activator.CreateInstance(nestedType);
// Recursively instantiate any further nested classes inside this instance
CreateInstancesOfAllClassesInside2(ref instance);
// Now invoke the constructor of the nested type to ensure proper initialization
ConstructorInfo[] ctors = nestedType.GetConstructors();
if (ctors.Length > 0)
{
ctors[0].Invoke(instance, (object[])null); // Call the constructor
}
// instances of nested classes do not appear in the object root! :-(
}
}
Вот пример класса, которому может потребоваться такая обработка:
Код: Выделить всё
public class _CONST
{
public class FOLDERS_APP
{
public class POSTS
{
public const string FOLDER_POSTS_USERS = "somefolder1/";
public const string FOLDER_PRO_POSTS_FROM_USERS = "somefolder2/";
public const string FOLDER_FOR_IM_IN_POST = "somefolder3/";
public const string FOLDER_ATTACH_TO_POSTS = "somefolder4/";
}
public class MANIFESTOS
{
public const string FOLDER_APPLICATION_MO = "somefolder5/";
public const string FOLDER_FOM_S = "somefolder6/";
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... -an-object
Мобильная версия