C # link understanding?

if I have:

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

in myFunc , a can access object b , but it can only refer (without casting) to a region in memory that is type A

what is understood.

In any case, the covariance seems that a can also access b : enter image description here

As you can see - it takes Enumerable from a and can still access its b typed objects


questions:

1 ) Well, how does he work behind the scenes? how can link a show me a larger object?

2 ) What should I do if I want to see property a1 from class a in a function? What should i change?

change

covariance:

Before C # 4, you couldn't go through the list: can't convert from 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'

An example of covariance and contravariance in the real world

+4
source share
3 answers

How can link A show me a larger object?

First of all, it is a smaller type. Every giraffe is an animal, but not every animal is a giraffe. Therefore, there are fewer giraffes in the world than there are animals in the world. Therefore, a giraffe is a smaller type than an animal.

Your type B is a smaller type than A. And, of course, a reference to a larger type may refer to something of a smaller type.

This has nothing to do with covariance. It always happens that IEnumerable<A> can give you B :

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

The list of animals may contain a giraffe. This has nothing to do with covariance.

Similarly, a link can always give you a smaller type back:

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

to those who say that this has nothing to do with covariance ...

Whatever sequence A may contain , B has nothing to do with covariance. What is involved with covariance is that sequence B can be converted to sequence A by reference conversion. Before covariant transforms were added in C # 4, this transform would fail.

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

You do not have to change anything; he is already working. Give it a try.

+6
source

As you can see - it accepts Enumerable of A, and it can still access its B-typed objects

The debugger shows it as B because it sees that its actual type is B. The code in myFunc can only access members of A, unless it passes an object to B.

+5
source

myFunc sees type B because you call it with one of myFunc(b);

You see a1 inside base class A

If you do

 static void Main(string[] args) { A a = new A(); myFunc(a); } 

you will see type A directly

Edit

Just to make it clear:

 void myFunc(A a) 

should read like

 void myFunc({Either A or something "larger" than A} a) 

with a large inheritance

0
source

Source: https://habr.com/ru/post/1394699/


All Articles