【问题标题】:access the common methods from each objects by iterating through a list通过遍历列表来访问每个对象的常用方法
【发布时间】:2012-12-03 01:36:49
【问题描述】:

我有多种类型的对象实例,它们继承自一个通用接口。 我想通过遍历列表或数组列表或集合来访问每个对象的常用方法。我该怎么做?

    {

    interface ICommon
    {
        string getName();
    }

    class Animal : ICommon
    {
        public string getName()
        {
            return myName;
        }
    }

    class Students : ICommon
    {
        public string getName()
        {
            return myName;
        }
    }

    class School : ICommon
    {
        public string getName()
        {
            return myName;
        }
    }


   }

当我在一个对象[]中添加动物、学生和学校,并尝试访问 在像

这样的循环中
for (loop)
{
   object[n].getName // getName is not possible here. 
   //This is what I would like to have.
or 
   a = object[n];
   a.getName // this is also not working. 
}

是否可以从列表或集合中访问不同类型的通用方法?

【问题讨论】:

    标签: c# arrays collections interface arraylist


    【解决方案1】:

    您需要将对象转换为ICommon

    var a = (ICommon)object[n];
    a.getName();
    

    或者你最好使用ICommon的数组

    ICommon[] commonArray = new ICommon[5];
    ...
    commonArray[0] = new Animal();
    ...
    commonArray[0].getName();
    

    或者您可能想考虑使用List<ICommon>

    List<ICommon> commonList = new List<ICommon>();
    ...
    commonList.Add(new Animal());
    ...
    commonList[0].getName();
    

    【讨论】:

      【解决方案2】:

      只需使用“ICommon”数组而不是“Object”数组,否则当您检索“Object”数组的项目时,您将不得不强制转换它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-17
        相关资源
        最近更新 更多