简体   繁体   中英

use a variable to store type

I want my program to be configurable what type of int it should use( most likely between int16 and int32 ) in order to save space.

I want to determine the type at the beginning of my code, so i just need to change one place instead of change all int16 to int32 .

Could there be something like:

Type myIntType = int16;// or int32
//just change here
.....
.....
//lost of use of myIntType
List<myIntType> arr = new List<myIntType>();
.....

In a small case the int list will hold numbers between 0 and 10,000 so UInt16 should be good.

But for large case the int list will hold numbers between 0 and 1,000,000 so should use Int32

I even wish there could be int20.

And the size of the list could be very large, so space intense.

You could use dynamic type in C# (I am not sure which version it was introduced in but the latest one should have it)

    List<dynamic> l = new List<dynamic>();
    dynamic d1 = 1;
    dynamic d2 = (Int16)1;

    l.Add(d1);
    l.Add(d2);
    //Your code goes here
    Console.WriteLine(d1.GetType());
    Console.WriteLine(d2.GetType());

    l.ForEach( x => Console.WriteLine(x.GetType()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM