Reflection deep to set default value

H

HarryZhao

Hi,
I'm using reflection and try to populate default value (ie. 0 for
integer,'' for string,etc) to an unknow object based on give type. The
following code is working only for two level of objects which means
the properties of object is object. I guess we need to have recursion
to do it. but how? I appreciate any idea or comments from you guys.
thank. Harry



static private object PopulateDefaultValue(Type t)
{
object docIn = Activator.CreateInstance(t);
FieldInfo[] myFieldInfo = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance
| BindingFlags.Public);

for(int i = 0; i < myFieldInfo.Length; i++)
{
Type t1 = myFieldInfo.FieldType;

if (t1.IsClass && !t1.Equals(Type.GetType("System.String")))
{
object docIn1 = Activator.CreateInstance(t1);

FieldInfo[] myFieldInfo1 = t1.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance
| BindingFlags.Public);

for(int j = 0; j < myFieldInfo1.Length; j++)
{
myFieldInfo1[j].SetValue(docIn1,
GetDefaultValue(myFieldInfo1[j]));
}
myFieldInfo.SetValue(docIn, docIn1);
}
else
{
myFieldInfo.SetValue(docIn, GetDefaultValue(myFieldInfo));
}

}
return docIn;
}

private static object GetDefaultValue(FieldInfo field)
{
Type t = field.FieldType;

object objVal = null;

//test only for case 1, not enough
if (t.Equals(Type.GetType("System.Int32")) )
objVal = 0;
else if (t.Equals(Type.GetType("System.Date")) )
objVal = System.DateTime.Now;
else
objVal = field.Name;


return objVal;
}
 
G

Guest

simple:

static private object PopulateDefaultValue(Type t)

object docIn = Activator.CreateInstance(t)
FieldInfo[] myFieldInfo = t.GetFields(BindingFlags.NonPublic
BindingFlags.Instanc
| BindingFlags.Public);

for(int i = 0; i < myFieldInfo.Length; i++

Type t1 = myFieldInfo.FieldType;
if (t1.IsClass && !t1.Equals(Type.GetType("System.String"))

object docIn1 = PopulateDefaultValue(t1)
myFieldInfo.SetValue(docIn, docIn1);


els

myFieldInfo.SetValue(docIn, GetDefaultValue(myFieldInfo))
}

return docIn
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top