我有一个基类:
public abstract class StuffBase
{
public abstract void DoSomething();
}
和两个派生类
public class Stuff1 : StuffBase
{
public void DoSomething()
{
Console.WriteLine("Stuff 1 did something cool!");
}
public Stuff1()
{
Console.WriteLine("New stuff 1 reporting for duty!");
}
}
public class Stuff2 : StuffBase
{
public void DoSomething()
{
Console.WriteLine("Stuff 2 did something cool!");
}
public Stuff1()
{
Console.WriteLine("New stuff 2 reporting for duty!");
}
}
好的,现在说我有一个项目列表:
var items = new List<StuffBase>();
items.Add(new Stuff1());
items.Add(new Stuff2());
我希望他们都调用他们的 DoSomething() 方法。我可以期望只迭代列表并调用他们的 DoSomething() 方法,所以假设我有一个名为 AllDoSomething() 的方法,它只是迭代列表并完成工作:
public static void AllDoSomething(List<StuffBase> items)
{
items.ForEach(i => i.DoSomething());
}
以下方法的实际区别是什么?
public static void AllDoSomething<T>(List<T> items) where T: StuffBase
{
items.ForEach(i => i.DoSomething());
}
这两种方法虽然在语法上有所不同,但实际上都是在做同样的事情。
它们只是做同一件事的不同方式吗?我了解泛型和类型约束,但不明白为什么在这种情况下我会使用一种方式而不是另一种方式。