Typeparameter set from type argument
How do I convert my argument to a proper type declaration. Ie. how do I go from type
to T
in the following
class Foo<T>
{
Foo<??> MakeFoo(Type type)
{
return new Foo<??>开发者_如何学运维;();
}
Void Get(T aFoo)
{
...
}
}
You cannot.
Generic parameters are used and applied by compiler while Type
is a part of Reflections that are designed to work with type information in run-time. So you just cannot define which type compiler should use if you have only System.Type
.
However you can do the opposite:
public void Foo<T>()
{
Type t = typeof(T);
}
So if you really do not need to use Type
as a parameter you can do the following:
Foo<FooParam> MakeFoo<FooParam>()
{
return new Foo<FooParam>();
}
You can't do such thing, because "Type" is a set of reflected metadata of classes, structures and/or enumerations.
"T" is the type.
You can give the type as argument using reflection:
type.MakeGenericType(type).GetConstructor(Type.EmptyTypes).Invoke(null)
But I'll vote to add a generic parameter "S" instead of input parameter "Type type" in order to avoid the use of reflection, which is useless in this case if you do it right!
精彩评论