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