【问题标题】:In C# hashtable with objects as values,how do i return the object value在以对象为值的 C# 哈希表中,我如何返回对象值
【发布时间】:2018-05-15 04:58:51
【问题描述】:

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

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

【问题讨论】:

  • 初始化这些值或将它们创建为 Auto Properties string name; string dob; int age; 对于初学者...
  • 必须解释投反对票

标签: c# object hashmap arguments hashtable


【解决方案1】:

您可以使用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();
}

甚至是带有显式实现的 EquiilityComparer 或覆盖 EqualsGetHashCode 的 HashSet。

【讨论】:

    【解决方案2】:

    首先,你应该在类中公开年龄属性,

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

    【讨论】:

      【解决方案3】:

      这就是你的做法:

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

      这里有两个建议。

      首先,您应该使用Dictionary&lt;string, theClass&gt; 之类的类型化集合,而不是HashtableHashtable 基本上已被弃用。泛型通常可以提高性能并减少引入类型安全错误的机会。在此处查看更多信息:https://docs.microsoft.com/en-us/dotnet/standard/collections/when-to-use-generic-collections

      Hashtable 的用法替换为Dictionary&lt;string, theClass&gt;,如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        • 2018-08-02
        • 2011-03-13
        • 2014-08-11
        • 1970-01-01
        相关资源
        最近更新 更多