c# - 通过遍历列表访问每个对象的公共(public)方法

标签 c# arrays collections interface arraylist

我有多种类型的对象实例,它们继承自一个公共(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/

相关文章:

java - 在 Java 中为 TreeMap 编写自定义排序时出现错误

c# - Entity Framework 附加/更新混淆(EF Core)

c# - 在 xml 中创建自己的设置

arrays - 将键上的对象数组和总和值减少到数组中

php - 名称数组 = 获取正确的文件

c# - 编写对集合中的第一项具有特殊逻辑的循环的巧妙方法

c# - Func 或 Predicate 到 ExpressionTree

c# - 当 C# 超出范围时,C# 是否自动将 "dispose"IDisposable 对象?

arrays - tensorflow 创建不同长度的掩码

java - 是否有人仍在使用 Vector(而不是 Collections.synchronizedList(List list)/CopyOnWriteArrayList)?