Type parameter specified from the type argument

How to convert an argument to a valid type declaration. I.e. how to go from typeto Tnext

class Foo<T>
{  
  Foo<??> MakeFoo(Type type)
  {
    return new Foo<??>();
  }

  Void Get(T aFoo)
  {
    ...
  }
}
+3
source share
2 answers

You can not.

General parameters are used and applied by the compiler, and Typeis part of Reflections, which are designed to work with type information at run time. Therefore, you simply cannot determine what type of compiler should be used if you only have one System.Type.

However, you can do the opposite:

public void Foo<T>()
{
  Type t = typeof(T);
}

So, if you really don't need to use Typeas a parameter, you can do the following:

Foo<FooParam> MakeFoo<FooParam>()
{
  return new Foo<FooParam>();
}
+5
source

, "" - , / .

"T" - .

, :

type.MakeGenericType(type).GetConstructor(Type.EmptyTypes).Invoke(null)

, "S" " ", , , !

+2

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


All Articles