在以对象作为值的C#哈希表中,如何返回对象值

时间:2017-12-01 05:56:51

标签: c# object hashmap arguments hashtable

方法CanVote returns true if Age >=18. 类的构造函数为所有属性分配默认值。 我将对象添加到哈希表中,密钥为Person Name。 我需要遍历hashtable对象来打印Name以及该人是否可以投票。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;*/

namespace HashTable
{
    class theClass
    {
        string name;
        string dob;
        int age;

        public theClass(string name,int age, string dob)
        {
            this.name = name;
            this.age = age;
            this.dob=dob;
        }

        public static string canvote(int age)
        {
            if (age >= 18)
                return "Can Vote";
            else
                return "Cnnot Vote";
        }
    }

    public class Solution
    {
        public static void Main()
        {
            Hashtable h = new Hashtable();
            theClass object1 = new theClass("John",16,"Chennai");
            theClass object2 = new theClass("Smita",22, "Delhi");
            theClass object3 = new theClass("Vincent",25, "Banglore");
            theClass object4 = new theClass("Jothi", 10, "Banglore");
            h.Add("John", object1);
            h.Add("Smita", object2);
            h.Add("Vincent", object3);
            h.Add("Jothi", object4);
            Console.WriteLine("df");
            Console.WriteLine(h.canvote());
            Console.ReadKey();
        }
    }
}

3 个答案:

答案 0 :(得分:0)

您就是这样做的:

foreach (var person in h.OfType<theClass>())
{
    Console.WriteLine($"{person.name} : {theClass.canvote(person.age)}");
}

这里有两条建议。

首先,您应该使用类似Dictionary<string, theClass>的类型集合,而不是HashtableHashtable基本上已被弃用。泛型通常会提高性能并降低引入类型安全漏洞的可能性。点击此处:https://docs.microsoft.com/en-us/dotnet/standard/collections/when-to-use-generic-collections

Hashtable的使用情况替换为Dictionary<string, theClass>,如下所示:

var h = new Dictionary<string, theClass>();
h.Add("John", object1);
h.Add("Smita", object2);
h.Add("Vincent", object3);
h.Add("Jothi", object4);

如果您将字段nameage设为公开字段:

foreach (var person in h.Values)
{
    Console.WriteLine($"{person.name} : {theClass.canvote(person.age)}");
}

其次,我建议您更改课程如下:

  • 将字段转换为属性。由于字段是从类外部访问的,因此属性是一种更好的机制,因为它可以防止外部代码以不受控制的方式更改类。

  • 公开这些属性,因为必须从课堂外访问这些属性。

  • 使canvote成为实例方法(非静态),如其他答案中所述。

请注意,属性只有getter。这意味着您的类现在是不可变的(即,初始化后无法更改对象)。如果您确实希望在初始化对象后更改这些值,则可以创建属性{ get; set; }

以下是完整列表:

class theClass
{
    public string name { get; }
    public string dob { get; }
    public int age { get; }

    public theClass(string name,int age, string dob)
    {
        this.name = name;
        this.age = age;
        this.dob=dob;
    }

    public string canVote()
    {
        if (age >= 18)
            return "Can Vote";
        else
            return "Cannot Vote";
    }
}

public class Solution
{
    public static void Main()
    {
        Dictionary<string, theClass> d = new Dictionary<string, theClass>();
        theClass object1 = new theClass("John",16,"Chennai");
        theClass object2 = new theClass("Smita",22, "Delhi");
        theClass object3 = new theClass("Vincent",25, "Banglore");
        theClass object4 = new theClass("Jothi", 10, "Banglore");
        d.Add("John", object1);
        d.Add("Smita", object2);
        d.Add("Vincent", object3);
        d.Add("Jothi", object4);

        foreach (var person in d.Values)
        {
            Console.WriteLine($"{person.name} : {person.canVote()}");
        }

        Console.ReadKey();
    }
}

答案 1 :(得分:0)

您可以使用Hashtable循环遍历foreach。另外我建议用公共属性替换静态canvote方法:

class theClass
{
    string name;
    string dob;
    int age;

    public theClass(string name, int age, string dob)
    {
        this.name = name;
        this.age = age;
        this.dob = dob;
    }

    public string CanVote => age >= 18 ? "Can Vote" : "Cannot Vote";  
}

public static void Main()
{
        Hashtable h = new Hashtable();
        theClass object1 = new theClass("John",16,"Chennai");
        theClass object2 = new theClass("Smita",22, "Delhi");
        theClass object3 = new theClass("Vincent",25, "Banglore");
        theClass object4 = new theClass("Jothi", 10, "Banglore");

        h.Add("John", object1);
        h.Add("Smita", object2);
        h.Add("Vincent", object3);
        h.Add("Jothi", object4);

        foreach(DictionaryEntry item in h){
            Console.WriteLine(item.Key);
            Console.WriteLine((item.Value as theClass).CanVote);
            Console.WriteLine();
        }

        Console.ReadKey();
}

使用强类型Dictionary<string, theClass>代替Hashtable可能更好:

public static void Main()
{
        Dictionary<string, theClass> dict = new Dictionary<string, theClass>{
           {"John", new theClass("John", 16, "Chennai")},
           {"Smita", new theClass("Smita", 22, "Delhi")},
           {"Vincent", new theClass("Vincent",25, "Banglore")},
           {"Jothi", new theClass("Jothi", 10, "Banglore")}
        };

        foreach(var item in dict){
            Console.WriteLine(item.Key);
            Console.WriteLine(item.Value.CanVote);
            Console.WriteLine();
        }

        Console.ReadKey();
}

甚至使用明确实现的EquilityComparer或覆盖EqualsGetHashCode的HashSet。

答案 2 :(得分:0)

首先,你应该在theClass中公开age property,

 Hashtable h = new Hashtable();
        theClass object1 = new theClass("John", 16, "Chennai");
        theClass object2 = new theClass("Smita", 22, "Delhi");
        theClass object3 = new theClass("Vincent", 25, "Banglore");
        theClass object4 = new theClass("Jothi", 10, "Banglore");

        h.Add("John", object1);
        h.Add("Smita", object2);
        h.Add("Vincent", object3);
        h.Add("Jothi", object4);


        foreach (DictionaryEntry entry in h)
        {
            //get the Class instance
            var tClass = (theClass) entry.Value;

            //call static canvote method, the age property must be public
            var message = theClass.canvote(tClass.age);

            Console.WriteLine("{0} => {1}", entry.Key, message);
        }