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

4

CanVote方法:如果年龄大于等于18岁,则返回true。 该类的构造函数将所有属性赋予默认值。 我将对象添加到哈希表中,以人名为键。 我需要遍历哈希表对象,打印出姓名和此人是否有投票权。

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();
        }
    }
}

首先,初始化这些值或将它们创建为“自动属性”:string name; string dob; int age; - MethodMan
https://www.dotnetperls.com/hashtable - MethodMan
下投票必须解释说明。 - felix-b
3个回答

2
你可以使用 foreach 循环遍历你的 Hashtable。此外,我建议用公共属性替换静态的 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或覆盖Equals和GetHashCode的HashSet。

2
首先,您应该在TheClass中将年龄属性设为公共属性。
 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);
        }

1

这就是如何做到的:

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

这里有两个建议。

首先,您应该使用一个类型化的集合,如Dictionary<string, theClass>,而不是HashtableHashtable基本上已经过时了。泛型通常可以提高性能并减少引入类型安全错误的机会。在此处查看更多信息:https://learn.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();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接