C# 0 The Complete Reference



Download 4,07 Mb.
Pdf ko'rish
bet381/1096
Sana23.01.2022
Hajmi4,07 Mb.
#402171
1   ...   377   378   379   380   381   382   383   384   ...   1096
Bog'liq
C-Sharp 3 The Complete Reference Herbert Schildt

X

 and class 



Y

 are physically the same, it is not possible to assign a 

reference of type 

Y

 to a variable of type 



X

 because they have different types. Therefore, this 

line is incorrect because it causes a compile-time type mismatch:

x2 = y; // Error, not of same type

In general, an object reference variable can refer only to objects of its type.

There is, however, an important exception to C#’s strict type enforcement. A reference 

variable of a base class can be assigned a reference to an object of any class derived from 

that base class. This is legal because an instance of a derived type encapsulates an instance 

of the base type. Thus, a base class reference can refer to it. Here is an example:

// A base class reference can refer to a derived class object.

using System;

class X {

  public int a;

  public X(int i) {

    a = i;

  }


}

class Y : X {

  public int b;

  public Y(int i, int j) : base(j) {

    b = i;

  }


}

class BaseRef {

  static void Main() {

    X x = new X(10);

    X x2;

    Y y = new Y(5, 6);

    x2 = x; // OK, both of same type

    Console.WriteLine("x2.a: " + x2.a);

    x2 = y; // OK because Y is derived from X

    Console.WriteLine("x2.a: " + x2.a);

www.freepdf-books.com



Download 4,07 Mb.

Do'stlaringiz bilan baham:
1   ...   377   378   379   380   381   382   383   384   ...   1096




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish