我有多种类型的对象实例,它们继承自一个公共(public)接口(interface)。 我想通过遍历列表或数组列表或集合来访问每个对象的通用方法。我该怎么做?
{
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.
}
是否可以从列表或集合中访问不同类型的公共(public)方法?
最佳答案
您需要将对象转换为 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();
关于c# - 通过遍历列表访问每个对象的公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13889059/