第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何讓程序知道父類的對(duì)象也是子類的對(duì)象

如何讓程序知道父類的對(duì)象也是子類的對(duì)象

C#
富國滬深 2023-09-24 16:17:16
我有一個(gè)具有某些字段的父抽象類,并且我還有一個(gè)具有附加字段的子類。有一個(gè)方法將父類的對(duì)象作為輸入,但如果我給它一個(gè)子類對(duì)象,我也需要使用它的字段。如果我直接這樣做會(huì)出錯(cuò)。我找不到訪問子字段的方法,并且在不將子字段設(shè)為父字段的情況下唯一可行的方法是創(chuàng)建對(duì)象的每個(gè)字段的數(shù)組。public abstract class Parent {    public int ParentIntField;    public void ParentMethod(Parent other)     {        if (other is Child)         {            int x = other.ChildIntField;            //do some job with other.ChildIntField        }        //maybe do some job with other.ParentIntField    }}public class Child: Parent{    public int ChildIntField;}PS 我對(duì) C# 很陌生,而且我的英語可能很糟糕,抱歉。
查看完整描述

2 回答

?
明月笑刀無情

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超4個(gè)贊

這是你可以做的:

投射物體

public abstract class Parent

{

? ? public int ParentIntField;

? ? public void ParentMethod(Parent other)

? ? {

? ? ? ? if (other is Child) /// Can do: (other is Child child) to avoid manually casting

? ? ? ? {

? ? ? ? ? ? Child childObject = (Child)other; // We are casting the object here.


? ? ? ? ? ? int x = childObject.ChildIntField;

? ? ? ? ? ? //do some job with other.ChildIntField

? ? ? ? }

? ? ? ? //maybe do some job with other.ParentIntField

? ? }

}


public class Child : Parent

{

? ? public int ChildIntField;

}

但請(qǐng)考慮重新考慮您的設(shè)計(jì):

但我會(huì)重新考慮你的設(shè)計(jì),因?yàn)槟阍谶@里違反了里氏替換規(guī)則。

這是重新設(shè)計(jì)的嘗試。如果您僅訪問與該特定實(shí)例關(guān)聯(lián)的變量,則無需將父對(duì)象傳遞到該方法中。如果您想訪問另一個(gè) Parent 對(duì)象,則必須將 Parent 參數(shù)添加回方法中。


public abstract class Parent

{

? ? public int ParentIntField;


? ? virtual public void Manipulate()

? ? {? ? ? ? ? ??

? ? ? ? //maybe do some job with other.ParentIntField

? ? }

}


public class Child : Parent

{

? ? public int ChildIntField;


? ? public override void Manipulate()

? ? {

? ? ? ? int x = ChildIntField; //do some job with ChildIntField? ? ? ? ? ??


? ? ? ? base.Manipulate();

? ? }

}


查看完整回答
反對(duì) 回復(fù) 2023-09-24
?
撒科打諢

TA貢獻(xiàn)1934條經(jīng)驗(yàn) 獲得超2個(gè)贊

作為一個(gè)抽象類,您可能希望避免處理子對(duì)象實(shí)例。與前面的答案一樣,嘗試在子級(jí)中重寫該方法,并且您可以使用“base”關(guān)鍵字調(diào)用基類功能。在 VS 中,當(dāng)您重寫時(shí),它會(huì)自動(dòng)注入該基本調(diào)用作為默認(rèn)語法。



查看完整回答
反對(duì) 回復(fù) 2023-09-24
  • 2 回答
  • 0 關(guān)注
  • 133 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)