DictionaryBase和子类对象方法

时间:2011-01-01 18:04:59

标签: c# class methods class-design

我正在使用DictionaryBase收集对象。但我无法获得子类(HardDrive.cs)方法只有超类,抽象,DeviceInfo方法如.Named();

Class HardDrive:DeviceInfo

deviceCollection = DictionaryBase

我正在尝试使用诸如Freespace,Size等的HardDrive方法

e.g。 它奏效了:

deviceCollection["Western Digital"].Named(); // Superclass method: Named

不起作用:

deviceCollection["Western Digital"].Size(); // Subclass method: Size

我不知道什么是可能的,它能够转换为子类吗?

提前谢谢。

文件名:DeviceInfo.cs

using System;
using System.Management;
using System.Windows.Forms;

namespace TestHarnessHardDrives
{
  public abstract class DeviceInfo
  {
    protected string name;

    public string Name
    {
      get
      {
        return name;
      }
      set
      {
        name = value;
      }
    }

    public DeviceInfo()
    {
      name = "The device with no name";
    }

    public DeviceInfo(string newName)
    {
      name = newName;
    }

    public void Named()
    {
      Console.WriteLine("{0} has been named.", name);
    }
  }
}

文件名:HardDrive.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestHarnessHardDrives
{
  class HardDrive: DeviceInfo
  {
    // properties
    private ulong _size;
    private ulong _freespace;
    private string _volumeSerialNumber;
    private string _filesystem;

    //methods

    // VolumeName + Caption
    public HardDrive(string newName, ulong newSize): base(newName)
    {
      _size = newSize;
    }

    // Freespace
    public ulong Freespace
    {
      get
      {
        return _freespace;
      }
      set
      {
        _freespace = value;
      }
    }

    // Size
    public ulong Size
    {
      get
      {
        return _size;
      }
      set
      {
        _size = value;
      }
    }

    // VolumeSerialNumber
    public string VolumeSerialNumber
    {
      get
      {
        return _volumeSerialNumber;
      }
      set
      {
        _volumeSerialNumber = value;
      }
    }

    // Filesystem
    public string Filesystem
    {
      get
      {
        return _filesystem;
      }
      set
      {
        _filesystem = value;
      }
    }
  }
}

filename:Devices.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestHarnessHardDrives
{
    class Devices: DictionaryBase
    {
        public void Add(string newID, DeviceInfo newDevice)
        {
            Dictionary.Add(newID, newDevice);
        }

        public void Remove(string newID, DeviceInfo oldDevice)
        {
            Dictionary.Remove(oldDevice);
        }

        public Devices()
        {
        }

        public DeviceInfo this [string deviceID]
        {
            get
            {
                return (DeviceInfo)Dictionary[deviceID];
            }
            set
            {
                Dictionary[deviceID] = value;
            }

        }

        public new IEnumerator GetEnumerator()
        {
            foreach (object device in Dictionary.Values)
                yield return (DeviceInfo)device;
        }
    }
}

....主程序

Filename: Program.cs
using System;
using System.Management;
using System.Windows.Forms;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestHarnessHardDrives
{
    class Program
    {
        public static Devices deviceCollection = new Devices();

        static void getHardDrives()
        {
            string keyHDDName;

            try
            {
                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_LogicalDisk");

                deviceCollection.Add("Western Digital", new HardDrive("Western Digital",100000));

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj["Description"].Equals("Local Fixed Disk"))
                    {
                        Console.WriteLine("Description: {0}", queryObj["Description"]);

                        keyHDDName = queryObj["VolumeName"].ToString() + " "
                                    + queryObj["Caption"].ToString();

                        deviceCollection.Add(keyHDDName, new HardDrive(keyHDDName, 100000));

                    };

                    //     Console.WriteLine("FileSystem: {0}", queryObj["FileSystem"]);
                    //     Console.WriteLine("FreeSpace: {0}", queryObj["FreeSpace"]);
                    //     Console.WriteLine("Size: {0}", queryObj["Size"]);
                    //     Console.WriteLine("VolumeSerialNumber: {0}", queryObj["VolumeSerialNumber"]);
                }

            }

        //      deviceCollection.Add(new SystemInterface("Western Digital"));

            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }


        static void Main(string[] args)
        {

            Console.WriteLine("Create an Array type Collection of DeviceInfo " +
                                    "objects and use it");

            getHardDrives();

            foreach (DeviceInfo myDevices in deviceCollection)
            {
                myDevices.Named();
                myDevices.GetType();
            }

            deviceCollection["Western Digital"].Named();

            Console.ReadKey();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

除非您有Devices课程中的更多代码,否则您根本不需要它 - 您只需使用Dictionary<DeviceInfo>

getHardDrives()方法中的要求似乎只是从设备字典中提取硬盘。

给定IDictionary<DeviceInfo>,您可以使用此行来获取硬盘:

var hardDrives = devices.Values.OfType<HardDrive>();

这将为您提供IEnumerable<HardDrive>

如果你想要字典中的键和值:

var hardDrivesAndIds = devices.Where(x => x.Value is HardDrive);

这将为您提供IEnumerable<KeyValuePair<string, DeviceInfo>>

另一种选择:

var hardDriveDictionary = devices.Where(x => x.Value is HardDrive).ToDictionary(x => x.Key, y => y.Value);

这将为您提供Dictionary<string, DeviceInfo>

答案 1 :(得分:0)

这是泛型的用途。继承自Dictionary而不是DictionaryBase。然后,您从集合中添加和删除的所有内容都将输入为HardDrive。更好,你甚至不需要继承...只是实例化一个字典。像这样......

var devices = new Dictionary<string, HardDrive>();

devices.Add("Western Digital", new HardDrive("WesternDigital"));
devices.Add("Seagate", new HardDrive("Seagate"));

所以你的主程序看起来像这样:

    namespace TestHarnessHardDrives
{
    class Program
    {
        public static Dictionary<string, HardDrive> deviceCollection = new Dictionary<string, HardDrive>

        static void getHardDrives()
        {
            string keyHDDName;

            try
            {
                ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_LogicalDisk");

                deviceCollection.Add("Western Digital", new HardDrive("Western Digital",100000));

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    if (queryObj["Description"].Equals("Local Fixed Disk"))
                    {
                        Console.WriteLine("Description: {0}", queryObj["Description"]);

                        keyHDDName = queryObj["VolumeName"].ToString() + " "
                                    + queryObj["Caption"].ToString();

                        deviceCollection.Add(keyHDDName, new HardDrive(keyHDDName, 100000));

                    };

                    //     Console.WriteLine("FileSystem: {0}", queryObj["FileSystem"]);
                    //     Console.WriteLine("FreeSpace: {0}", queryObj["FreeSpace"]);
                    //     Console.WriteLine("Size: {0}", queryObj["Size"]);
                    //     Console.WriteLine("VolumeSerialNumber: {0}", queryObj["VolumeSerialNumber"]);
                }

            }

        //      deviceCollection.Add(new SystemInterface("Western Digital"));

            catch (ManagementException e)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
            }
        }


        static void Main(string[] args)
        {

            Console.WriteLine("Create an Array type Collection of DeviceInfo " +
                                    "objects and use it");

            getHardDrives();

            foreach (DeviceInfo myDevices in deviceCollection)
            {
                myDevices.Named();
                myDevices.GetType();
            }

            deviceCollection["Western Digital"].Named();

            Console.ReadKey();
        }
    }
}

注意:到目前为止我写的所有东西只适用于你想要一个只有HardDrives的集合。如果你有一些其他类型的设备也继承自你的基本Device类,但有自己的方法,那么单独的泛型不足以解决你的问题。此时,您可以将所有内容存储为Device类型的集合,并使用类型检查将其强制转换为完整类型,否则您将被迫将不同的设备类型放入不同的集合中。