开发者

C#: Storing Instance of Objects in (Hashtable)

开发者 https://www.devze.com 2023-01-02 05:40 出处:网络
Hi I tried filling a Hashtable in the following way: ResearchCourse resCourse= new ResearchCourse();//Class Instance

Hi I tried filling a Hashtable in the following way:

      ResearchCourse resCourse= new ResearchCourse();//Class Instance
      resCourse.CID="RC1000";
      resCourse.CName="Rocket Science";

      TaughtCourse tauCourse= new TaughtCourse();//Class Instance
      tauCourse.CID="TC1000";
      tauCourse.CName="Marketing";

      Hashtable catalog = new Hashtable();

        catalog.Add("1", "resCourse.CID");
        catalog.Add("2", "tauCourse.CID");


        foreach (DictionaryEntry de in catalog)
        {
            Console.WriteLine("{0}, {1}", de.Key, de.Value);
        }

Output Result to Console was:

1, resCourse.CID

2, tauCourse.CID

Expected Result to be:

1, RC1000

2, TC2000

What am I misunderstanding about Hashtables?

What is an easy way for the Hashtable to store the class instance and its values?开发者_如何学Go


HashTable just maps keys to values. You map the string "1" to the string "resCourse.CID" so the results you get are completely normal. Do it like this way:

catalog.Add("1", resCourse.CID);
catalog.Add("2", tauCourse.CID);

Now you will map the real values you need, not the string "resCourse.CID".


You're adding explicit strings to the hash table instead of actual IDs.

Replace the two catalog.Add lines with:

catalog.Add("1", resCourse.CID);
catalog.Add("2", tauCourse.CID);

No quotation marks around the values.


Remove the quotes around resCourse.CID and tauCourse.CID in your catalog.Add statements. You're adding the literal strings, not the value of the properties.


I'm assuming that you'll actually want to store the entire objects:

catalog.Add("1", resCourse);
catalog.Add("2", tauCourse);

Of course, once you go there you're going to have to have a common base class (or interface) for your two courses to derive from in order to access the values:

public abstract class CourseBase {
   public string CID { get; set; }
   public string CName{ get; set; }
}

public class ResearchCourse : CourseBase { }
public class TaughtCourse : CourseBase { }

Then you can store/access like this:

Hashtable catalog = new Hashtable();
catalog.Add("1", resCourse);
catalog.Add("2", tauCourse);

foreach (DictionaryEntry de in catalog) 
{
   Console.WriteLine("{0}, {1}", de.Key, ((CourseBase)de.Value).CID);
}

Or better yet, use a generic Dictionary:

    var resCourse = new ResearchCourse() { CID = "RC1000", CName = "Rocket Science" };
    var tauCourse = new ResearchCourse() { CID = "TC1000", CName = "Marketing" };

    var catalog = new Dictionary<string, CourseBase>();
    catalog.Add("1", resCourse);
    catalog.Add("2", tauCourse);

    foreach (string key in catalog.Keys)
    {
        Console.WriteLine("{0}, {1}", key, catalog[key].CID);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消