通过迭代列表来访问每个对象的常用方法

GMa*_*ika 4 c# arrays collections interface arraylist

我有多种类型的对象实例从公共接口继承.我想通过迭代列表或arraylist或集合来访问每个对象的常用方法.我怎么做?

    {

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


   }
Run Code Online (Sandbox Code Playgroud)

当我在对象[]中添加动物,学生和学校时,尝试以类似的循环访问

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. 
}
Run Code Online (Sandbox Code Playgroud)

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

juh*_*arr 6

您需要将对象强制转换为 ICommon

var a = (ICommon)object[n];
a.getName();
Run Code Online (Sandbox Code Playgroud)

或者最好你应该使用一个数组 ICommon

ICommon[] commonArray = new ICommon[5];
...
commonArray[0] = new Animal();
...
commonArray[0].getName();
Run Code Online (Sandbox Code Playgroud)

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

List<ICommon> commonList = new List<ICommon>();
...
commonList.Add(new Animal());
...
commonList[0].getName();
Run Code Online (Sandbox Code Playgroud)