dimanche 8 mars 2015

createinstance Recursively using Reflection

i wrote a method as below to createinstance for givin type, but it doesn't work, anyone else can help to take a look at


public static object CreateInstance(Type type, bool genParam) { #region if generate parameter if (!genParam) { try { return Activator.CreateInstance(type); } catch { } } #endregion



List<MethodBase> candidates = new List<MethodBase>();
object ret = GetNewInstanceForKnownTypes(type);
if (ret != null) return ret;

MethodBase[] ctors = type.GetConstructors();
candidates.AddRange(ctors);

MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
if (method.IsStatic && method.ReturnType.Equals(type))
candidates.Add(method);
for (int j = 0; j < candidates.Count; j++)
{

ParameterInfo[] paramInfo = candidates[j].GetParameters();
object[] parameters = new object[paramInfo.Length];
try
{
foreach (ParameterInfo pi in paramInfo)
if (pi.ParameterType.Equals(type))
throw new Exception();

for (int i = 0; i < paramInfo.Length; i++)
{
parameters[i] = GetNewInstanceForKnownTypes(paramInfo[i].ParameterType);
if (parameters[i] != null) continue;

#region if type is abstract or interface
if (paramInfo[i].ParameterType.IsAbstract || paramInfo[i].ParameterType.IsInterface)
{
parameters[i] = null;
continue;
}
#endregion

#region if type is array
if (paramInfo[i].ParameterType.IsArray)
{
try
{
Type arrItemType = Type.GetType(paramInfo[i].ParameterType.FullName.Replace("[]", string.Empty));
object arrItem = CreateInstance(arrItemType, genParam);
object[] arr = (object[])Activator.CreateInstance(paramInfo[i].ParameterType, 1);
arr[0] = arrItem;
parameters[i] = arr;
continue;
}
catch { }
}
#endregion

#region if type is enum
if (paramInfo[i].ParameterType.IsEnum)
{
parameters[i] = 0;
continue;
}
#endregion
if (paramInfo[i].ParameterType.GetConstructor(Type.EmptyTypes) != null)
{
parameters[i] = Activator.CreateInstance(paramInfo[i].ParameterType);
continue;
}

parameters[i] = CreateInstance(paramInfo[i].ParameterType, genParam);
}


if (candidates[j] is ConstructorInfo)
ret = Activator.CreateInstance(type, parameters);
else
ret = candidates[j].Invoke(null, parameters);

if (ret != null)
break;
}

catch (Exception){ }
}
return ret;
}





Aucun commentaire:

Enregistrer un commentaire