() { object x = Activator.CreateInst...">

Type as a common "T" using reflection

Is it possible for me to do the following?

public static T Merge<T>()
{
     object x = Activator.CreateInstance<T>();
     //Do some stuff with x 
     return (T)x;
}

private static Type[] GetTypesInNamespace(Assembly assembly, string nameSpace)
{
    return assembly.GetTypes().Where(
        t => String.Equals(t.Namespace, nameSpace, StringComparison.Ordinal) & 
             !t.IsInterface).ToArray();
}

public static void Main()
{
    Type[] typelist = GetTypesInNamespace(
        Assembly.GetExecutingAssembly(), "Myapplication.Web.DomainObjects");

    Parallel.ForEach(typelist, type =>
    {
        var  task1 = Task.Factory.StartNew(() => Merge<type>());
        // is it possible to do this way? Merge<type> ??    
    });
}
+3
source share
2 answers

No, you cannot do this - Generics are used when you know the type in advance at compile time, but in this case you do not use.

I believe that what you really want to do is something like this:

public static object Merge(Type type)
{
    object x = Activator.CreateInstance(type);
    //Do some stuff with x 
    return x;
}

Your foreach statement looks a little different:

Parallel.ForEach(typelist, type =>
{
    var task1 = Task.Factory.StartNew(() => Merge(type));
});
0
source

If you want to call a generic method with a type that you do not know at compile time, you need to use reflection:

  Parallel.ForEach(typelist, type => {
    var methodInfo = typeof(YourClass).GetMethod("Merge").MakeGenericMethod(type);
    var  task1 = Task.Factory.StartNew(() => methodInfo.Invoke(null, new object[0]));
  });
0
source

Source: https://habr.com/ru/post/1758871/


All Articles