无法在 C# 中使用协变/逆变

发布于 2024-10-30 23:40:17 字数 484 浏览 9 评论 0原文

abstract class A<T> {
  List<T> Items { get; set; }
}

class B {}
class C : A<B> {}

class D : B {}
class E : A<D> {}

static class X {
  public A<B> GetThing(bool f) {
    return f ? new E() : new C();
  }
}

无法确定条件表达式的类型,因为“ConsoleApplication4.E”和“ConsoleApplication4.C”之间没有隐式转换

现在我明白了“为什么”(我认为),但我不知道如何进行编译。我想我必须创建一个接口来定义某种差异并从中继承,但我不确定。但无论如何,E() 应该继承自 C()

有接受者吗?

TIA

abstract class A<T> {
  List<T> Items { get; set; }
}

class B {}
class C : A<B> {}

class D : B {}
class E : A<D> {}

static class X {
  public A<B> GetThing(bool f) {
    return f ? new E() : new C();
  }
}

Type of conditional expression cannot be determined because there is no implicit conversion between 'ConsoleApplication4.E' and 'ConsoleApplication4.C'

Now I get the "why" (I think) but I can't see how to make this compile. I think I have to create an interface which defines variance of some kind and inherit from that, but I'm not sure. But regardless, E() should inherit from C().

Any takers?

TIA

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独夜无伴 2024-11-06 23:40:17

要在 C# 中使用泛型变体,您必须满足以下全部条件:

  1. 使用 C# 4
  2. 变体的类型必须是泛型接口或泛型委托
  3. 类型参数必须标记为“in”(逆变)或“out”(协变)
  4. 类型参数注释必须生成一个在所有可能的操作中可证明类型安全的类型
  5. “源”类型参数和“目标”类型参数必须在它们之间具有标识或引用转换。

您的程序满足条件 1 和条件 5,但不满足条件 2、3 或 4。

无法获得所需的方差,因为您想要的东西会违反条件 4。观察当我们满足除条件 4 之外的所有条件时会发生什么:

// Suppose this declaration were legal:
interface IMyCollection<out T> 
{
  List<T> Items { get; set; } 
}

class Animal {}
class AnimalCollection : IMyCollection<Animal> 
{ 
  public List<Animal> { get; set; }
}

class Giraffe : Animal {}
class GiraffeCollection : IMyCollection<Giraffe> 
{
  public List<Giraffe> { get; set; } 
}

static class X 
{
  public IMyCollection<Animal> GetThing() 
  {
    // IMyCollection is covariant in T, so this is legal.
    return new GiraffeCollection(); 
  }
}

class Tiger : Animal {}

...

IMyCollection<Animal> animals = X.GetThing(); 
// GetThing() actually returns a GiraffeCollection
animals.Items = new List<Animal>() { new Tiger(); }

长颈鹿集合现在包含包含老虎的动物列表。

如果要使用方差,则必须是类型安全的。由于编译器无法确定方差注释是否是类型安全的,因此它会拒绝 IMyCollection 的声明。

让我们看看如何做到这一点并保持类型安全。 问题是 Items 可以通过接口进行写入。

interface IMyCollection<out T> 
{
  IEnumerable<T> Items { get; }
}

class Animal {}
class AnimalCollection : IMyCollection<Animal> 
{ 
  public IEnumerable<Animal> { get { yield return new Tiger(); } }
}

class Giraffe : Animal {}
class GiraffeCollection : IMyCollection<Giraffe> 
{
  public IEnumerable<Giraffe> { get { yield return new Giraffe(); } } 
}

static class X 
{
  public IMyCollection<Animal> GetThing() 
  {
    return new GiraffeCollection();
  }
}

class Tiger : Animal {}

...

MyCollection<Animal> animals = X.GetThing(); 
// GetThing() actually returns a GiraffeCollection
foreach(Animal animal in animals.Items) { ... } 
// Items yields a giraffe, which is an animal

完全类型安全。这将是一个合法的 C# 4 程序。

如果您对 C# 4 中协变和逆变的设计细节感兴趣,您可以考虑阅读我关于该主题的十几篇文章。您可以在这里找到它们:

http://blogs.msdn。 com/b/ericlippert/archive/tags/covariance+and+contravariance/

请注意,这些是按从最近到最近的顺序列出的;从底部开始。

如果您特别对确定接口注释何时有效的规则感兴趣,请参阅这篇文章(我刚刚发现并修复了其中的一些错误,所以我很高兴我们进行了这次对话。)

http://blogs.msdn.com/b/ ericlippert/archive/2009/12/03/exact-rules-for-variance-validity.aspx

To use generic variance in C# you have to meet all the following conditions:

  1. Use C# 4
  2. The type that varies must be a generic interface or generic delegate
  3. The type parameter must be marked "in" (contravariant) or "out" (covariant)
  4. The type parameter annotations must yield a type which is provably typesafe in all its possible operations
  5. The "source" type argument and the "destination" type argument must have an identity or reference conversion between them.

Your program meets condition 1 and condition 5 but not conditions 2, 3, or 4.

There is no way to get the variance you want because you want something that would violate condition 4. Watch what happens when we meet all the conditions except condition 4:

// Suppose this declaration were legal:
interface IMyCollection<out T> 
{
  List<T> Items { get; set; } 
}

class Animal {}
class AnimalCollection : IMyCollection<Animal> 
{ 
  public List<Animal> { get; set; }
}

class Giraffe : Animal {}
class GiraffeCollection : IMyCollection<Giraffe> 
{
  public List<Giraffe> { get; set; } 
}

static class X 
{
  public IMyCollection<Animal> GetThing() 
  {
    // IMyCollection is covariant in T, so this is legal.
    return new GiraffeCollection(); 
  }
}

class Tiger : Animal {}

...

IMyCollection<Animal> animals = X.GetThing(); 
// GetThing() actually returns a GiraffeCollection
animals.Items = new List<Animal>() { new Tiger(); }

And a giraffe collection now contains a list of animals that contains a tiger.

You have to be typesafe if you're going to use variance. Because the compiler cannot determine the variance annotations to be typesafe, it rejects the declaration of IMyCollection.

Let's see how we might do this and be typesafe. The problem is that Items is writable via the interface.

interface IMyCollection<out T> 
{
  IEnumerable<T> Items { get; }
}

class Animal {}
class AnimalCollection : IMyCollection<Animal> 
{ 
  public IEnumerable<Animal> { get { yield return new Tiger(); } }
}

class Giraffe : Animal {}
class GiraffeCollection : IMyCollection<Giraffe> 
{
  public IEnumerable<Giraffe> { get { yield return new Giraffe(); } } 
}

static class X 
{
  public IMyCollection<Animal> GetThing() 
  {
    return new GiraffeCollection();
  }
}

class Tiger : Animal {}

...

MyCollection<Animal> animals = X.GetThing(); 
// GetThing() actually returns a GiraffeCollection
foreach(Animal animal in animals.Items) { ... } 
// Items yields a giraffe, which is an animal

Perfectly typesafe. This would be a legal C# 4 program.

If the design details of covariance and contravariance in C# 4 interests you, you might consider reading my dozen articles on the subject. You can find them here:

http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/

Note that these are listed in most-to-least-recent order; start from the bottom.

If in particular you are interested in the rules for determining when an interface's annotations are valid, see this article (which I just discovered and fixed some errors in, so I'm glad we had this conversation.)

http://blogs.msdn.com/b/ericlippert/archive/2009/12/03/exact-rules-for-variance-validity.aspx

难得心□动 2024-11-06 23:40:17

EC 之间没有关系。因此,您的返回类型必须是 A,它可以被视为这些类型的公共父级。此外,A 需要是一个接口,其中通用参数是使用 out 定义的,这样才能正常工作:

interface A<out T> { }

class B { }
class C : A<B> { }

class D : B { }
class E : A<D> { }

static class X
{
    public static A<B> GetThing(bool f)
    {
        if (f)
        {
            return new E();
        }
        return new C();
    }
}

无法使其与 三元运算符 (?:)。编译器根本不喜欢它。


更新:

在 @Eric Lippert 在评论部分的精彩评论之后,您可以通过转换为 A 来使用三元运算符:

public static A<B> GetThing(bool f)
{
    return f ? (A<B>)new E() : new C();
}

There is no relation between E and C. So your return type must be A<B> which may be considered as a common parent to those types. Also A needs to be an interface where the generic argument is defined with out for this to work:

interface A<out T> { }

class B { }
class C : A<B> { }

class D : B { }
class E : A<D> { }

static class X
{
    public static A<B> GetThing(bool f)
    {
        if (f)
        {
            return new E();
        }
        return new C();
    }
}

Couldn't make it work with the ternary operator (?:). The compiler simply doesn't like it.


UPDATE:

After @Eric Lippert's excellent remark in the comments section you could use the ternary operator by casting to A<B>:

public static A<B> GetThing(bool f)
{
    return f ? (A<B>)new E() : new C();
}
可爱咩 2024-11-06 23:40:17

这是行不通的,因为 CE 没有共同的父级。对于这样的事情,您需要创建一个通用的父类型,无论是类还是接口。

This cannot work because C and E have no common parent. To something like this you need to create a common parent type, be it a class or an interface.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文