c#引用理解?

标签 c# .net-4.0 covariance

如果我有:

   public class A {   public int a1;}
   public class B : A {  public int b1;}

   void myFunc(A a) 
   {}

  static void Main(string[] args)
       {
         B b = new B();
         myFunc(b);
       }

myFunc 中,a 可以访问 b 对象,但它只能引用(不强制转换)到内存中的区域 类型 A

明白了。

然而在协方差中似乎a也可以访问b: enter image description here

如您所见 - 它接受 A 的 Enumerable 并且它仍然可以访问其 B 类型的对象


问题:

1) 好的,它在幕后是如何工作的? A 引用如何向我展示一个更大的 对象?

2) 如果我想在函数中看到 A 类的 a1 属性怎么办?我应该更改什么?

编辑

协方差相关:

Before C# 4, you couldn't pass in List: cannot convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'

Covariance and contravariance real world example

最佳答案

How can an A reference can show me a larger object?

首先,它是一种较小的类型。每只长颈鹿都是动物,但不是每只动物都是长颈鹿。因此,世界上长颈鹿的数量少于世界上的动物数量。因此长颈鹿是比动物小的种类。

您的类型 B 是一个比 A 小的类型。当然,对较大类型的引用可以引用较小类型的东西。

这与协方差无关。 IEnumerable<A> 总是这样。可以给你一个B :

List<A> myList = new List<A>() { new B(); } // No covariance here
Console.WriteLine(myList[0].GetType()); // it's a B.

动物列表可以包含长颈鹿。这与协方差无关。

同样,引用总是可以返回一个更小的类型:

A a = new B(); // Legal!

to those who says it has nothing to do with covariance...

A 的序列可以包含 B 与协变性无关。与协变有关的是可以通过引用转换将 B 的序列转换为 A 的序列。在将协变转换添加到 C# 4 之前,该转换会失败。

What if i wanted to see in the function the a1 property from the A class? what should I change?

你不应该改变任何东西;它已经工作了。试试吧。

关于c#引用理解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135917/

相关文章:

C# CSV 解析转义双引号

.net - 身份、WIF、SAML 和第 3 方 IdP

c# - 在长时间运行的 Windows 服务中使用计时器

scala - 为协变集合添加 `to[Col[_]]` 方法

c# - 使用 linq 表达式的协变/逆变

c# - 如何将 FlowDocument 添加到 StackPanel?

c# - 如何删除罗斯林?

c# - SslStream.Read() 的奇怪行为

参数中的 C++ 协方差

c# - Facebook 的 MVC 4 授权问题