Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过遍历列表从每个对象访问公共方法_C#_Arrays_Collections_Interface_Arraylist - Fatal编程技术网

C# 通过遍历列表从每个对象访问公共方法

C# 通过遍历列表从每个对象访问公共方法,c#,arrays,collections,interface,arraylist,C#,Arrays,Collections,Interface,Arraylist,我有多种类型的对象实例,它们从公共接口继承。 我希望通过遍历列表、arraylist或集合来访问每个对象的常用方法。我该怎么做 { interface ICommon { string getName(); } class Animal : ICommon { public string getName() { return myName; } }

我有多种类型的对象实例,它们从公共接口继承。 我希望通过遍历列表、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;
        }
    }


   }
当我在对象[]中添加动物、学生和学校,并尝试访问 成环状

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

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

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

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

var a = (ICommon)object[n];
a.getName();
ICommon[] commonArray = new ICommon[5];
...
commonArray[0] = new Animal();
...
commonArray[0].getName();
或者最好使用
ICommon

var a = (ICommon)object[n];
a.getName();
ICommon[] commonArray = new ICommon[5];
...
commonArray[0] = new Animal();
...
commonArray[0].getName();

或者您可能想考虑使用<代码>列表<代码> < /p>

List commonList=new List();
...
commonList.Add(新动物());
...
commonList[0]。getName();