gpt4 book ai didi

c# - 我什么时候应该或不应该使用泛型类型约束?

转载 作者:行者123 更新时间:2023-11-30 20:13:54 25 4
gpt4 key购买 nike

我有一个基类:

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());
}

虽然语法不同,但实际上这两种方法都在做同样的事情。

它们只是做同一件事的不同方式吗?我了解泛型和类型约束,但不明白为什么在这种情况下我会使用一种方式而不是另一种方式。

最佳答案

这是因为到目前为止,C# 还不支持 Covariance .

More formally, in C# v2.0 if T is a subtype of U, then T[] is a subtype of U[], but G is not a subtype of G (where G is any generic type). In type-theory terminology, we describe this behavior by saying that C# array types are “covariant” and generic types are “invariant”.

引用:http://blogs.msdn.com/rmbyers/archive/2005/02/16/375079.aspx

如果你有以下方法:

public static void AllDoSomething(List<StuffBase> items)
{
items.ForEach(i => i.DoSomething());
}

var items = new List<Stuff2>();
x.AllDoSomething(items); //Does not compile

如果您使用泛型类型约束,它会。

有关协变和逆变的更多信息],请查看 Eric Lippert's series of posts .


其他值得一读的帖子:

关于c# - 我什么时候应该或不应该使用泛型类型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1219573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com