0
我想要一個ArrayList,您可以在其中添加實現接口的對象。 類似這樣的:ArrayList與實現接口的對象
ArrayList<Object implements Interface> list =
new ArrayList<Object which implements a specific Interface>();
這是什麼正確的語法?
我想要一個ArrayList,您可以在其中添加實現接口的對象。 類似這樣的:ArrayList與實現接口的對象
ArrayList<Object implements Interface> list =
new ArrayList<Object which implements a specific Interface>();
這是什麼正確的語法?
只需將接口設置爲通用類型即可。在這裏你去C#代碼:
interface IFoo {
void foo();
}
class Foo1 : IFoo {
public void foo() {
Console.WriteLine("foo1");
}
}
class Foo2 : IFoo {
public void foo() {
Console.WriteLine("foo2");
}
}
class Program {
public static void Main() {
// IFoo type: any object implementing IFoo may go in
List<IFoo> list = new List<IFoo>();
list.Add(new Foo1());
list.Add(new Foo2());
foreach(IFoo obj in list) obj.foo(); // foo1, foo2
Console.ReadKey();
}
}
閱讀有關泛型。 –
如何從ArrayList繼承並實現接口? – hpd
我不想讓ArrayList實現接口,我想讓ArrayList中的對象實現接口。 – ShroomPow