Creating an instance of the Generic class using a field type at run time

The first question is here. I am trying to instantiate a generic class using a field type.

public class ValueRange<type1>
{
    type1 min;
    type1 max;
}

void foo()
{
    int k;
    ValueRange<k.GetType()> range;  
}

This does not work. Any suggestions?
thanks in advance

+3
source share
4 answers

Compile time type required:

ValueRange<int> range;

It's also worth noting that you usually name your types “T”; it is just a generally accepted standard (and therefore a pleasure to read).

+6
source

The sample is confused. I suspect you want something like

Type genericType = typeof(ValueRange<>).MakeGenericType(k.GetType());
Activator.CreateInstance(genericType);
+8
source

, , .

Type genericType = typeof(ValueRange<>).MakeGenericType(k.GetType());
object instance = Activator.CreateInstance(genericType);

.NET 4.0 , . .

: , genericType .

+1

Make it clearer. In the above example, ValueRange is my class, not C # one.

I wonder if there is a way to avoid type declaration twice.

int k;
ValueType m;

In this declaration, the type "int" is declared twice. But it seems to me superfluous. If, for example, I want to change type k, I would have to change both declarations. I knew about Activator.CreateInstance, but it doesn’t look beautiful to me! Too complicated !! But if there is no better solution, I will stick to it

+1
source

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


All Articles