C # - can convert from type C # to System.Type, but not vice versa

I can create a general class that takes a C # type as a template parameter, and then uses the System.Type information corresponding to this C # type in the general class:

public class Generic<T>
{
    public bool IsArray()
    {
        return typeof(T).IsArray();
    }
    public T Create()
    {
        return blah();
    }
}
Generic<int> gi = new Generic<int>();
Debug.WriteLine("int isarray=" + gi.IsArray());
Generic<DateTime> gdt;

But now say what I have is System.Type. I cannot use this to instantiate my generic class:

FieldInfo field = foo();
Generic<field.FieldType> g;   // Not valid!

Is there some clever C # thing that I can do to convert System.Type back to the original C # type? Or in some other way to create a generic one that can (1) provide me with information about System.Type and (2) create objects of the associated C # type?

By the way, this is a very far-fetched example to explain the problem I'm trying to solve, don’t worry too much about whether it makes sense or not!

+4
1

, , . , int Generic<int> , field.FieldType .

:

Type type = typeof(Generic<>).MakeGenericType(field.FieldType);

// Object of type Generic<field.FieldType>
object gen = Activator.CreateInstance(type);

, Type (field.FieldType), Type (Type)

:

  • : Generic<type> . Activator.CreateInstance, Type.GetMethod() Invoke()

Type type = typeof(Generic<>).MakeGenericType(field.FieldType);

// Object of type Generic<field.FieldType>
object gen = Activator.CreateInstance(type);
MethodInfo isArray = type.GetMethod("IsArray");
bool result = (bool)isArray.Invoke(gen, null);
  • / : , Generic<T>. / .

public class Generic<T> : IComparable where T : new()
{
    public bool IsArray()
    {
        return typeof(T).IsArray;
    }

    public T Create()
    {
        return new T();
    }

    public int CompareTo(object obj)
    {
        return 0;
    }
}

Type type = typeof(Generic<>).MakeGenericType(field.FieldType);
IComparable cmp = (IComparable)Activator.CreateInstance(type);
int res = cmp.CompareTo(cmp);
  • , Generic<T>. , .

public static void WorkWithT<T>() where T : new()
{
    Generic<T> g = new Generic<T>();
    T obj = g.Create();
    Console.WriteLine(g.IsArray());
}

var method = typeof(Program).GetMethod("WorkWithT").MakeGenericMethod(field.FieldType);

// Single reflection use. Inside WorkWithT no reflection is used.
method.Invoke(null, null); 
+3

All Articles