How to declare an instance that its type is defined by the user in C #

Just my question is determining the type of the instance at runtime, and that type is user-defined. Something like this:

Type instance1;

At run time, the user is going to select, for example, "int", then there will be

int instance1;

Any suggestions? is downCasting effective here?

+3
source share
4 answers

What you are looking for is generics. Read the introduction here .

For example, you must declare a class that must be specified by a user-specified type:

class MyClass<T>
{
    private T instance1 = default(T);

    public MyClass(T initalvalue)
    {
        instance1 = initalvalue;
    }

    //... some more code
}
+2
source

, , * # 4 dynamic , .

* , , , compile-time (.. int, char double, ). , generic , .

+1

# 4.0

0

, , :

Type myType = typeof(int);
int value = Activatior.CreateInstance(myType);

In .NET 4, a dynamic keyword is perhaps more efficient and convenient.

0
source

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


All Articles