简体   繁体   中英

What datatype to use in C# class?

In school, for a C# course, they gave us a very mystical assignment. There is the following code in Main() and we have to write the class Group .

Group group = new Group(3);
group["wholenumber"] = 123;
group["decimalnumber"] = 456.78;
group["text"] = "Hello world!";

double sum = (double)(int)group["wholenumber"] + (double)group["decimalnumber"];
Console.WriteLine("Sum of numbers is {0}", sum);

Does that make any sense? I thought you cant use strings as index? I would understand if there was variable names as index, so they could pass for finals, but now I don't get it. I tried to use Google and found dictionaries which are like arrays and can use a string as an index, but all values are different - first is int, second double and last is string, so dictionary won't work.

At the moment we are talking about static classes, constants, destructors and indexers

Thanks in advance

Since you mention that you are currently talking about indexers, this is exactly what you need to implement for your Group class (assuming that the code in main is fixed and you need to make a class work for that code).

According to MSDN: Indexers (C# Programming Guide) :

Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.

So in this case, you could have code like:

public class Group
{
    public object this[string s]
    {
        get
        {
            //return something based on "s"
        }
        set
        {
            //set something based on "s"
        }
    }
}

but all values are different - first is int, second double and last is string, so dictionary wont work.

Actually it will as System.object is a common base class. THis is why all retrievals from the Group have a cast. Not that this Group "class" makes any logical sense - noone would write a separate class for this, everyone I know would jst write:

var group = new Dictionary<string,object> (3);

Note that group is a terrible variable name due to being a keyword.

You could use Dictionary<TKey, TValue> as some guys said, but you could inherit from it, for sample:

public class Group : Dictionary<string, object>
{
}

And use like a dictionary:

Group g = new Group();
g.Add("wholenumber", 123);
g.Add("decimalnumber", 456.78);
g.Add("text", "Hello world!");

the problem to read is the value is an object , and you need to cast it to right type.

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