亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓程序知道父類的對象也是子類的對象

如何讓程序知道父類的對象也是子類的對象

C#
富國滬深 2023-09-24 16:17:16
我有一個具有某些字段的父抽象類,并且我還有一個具有附加字段的子類。有一個方法將父類的對象作為輸入,但如果我給它一個子類對象,我也需要使用它的字段。如果我直接這樣做會出錯。我找不到訪問子字段的方法,并且在不將子字段設為父字段的情況下唯一可行的方法是創建對象的每個字段的數組。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 我對 C# 很陌生,而且我的英語可能很糟糕,抱歉。
查看完整描述

2 回答

?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

這是你可以做的:

投射物體

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;

}

但請考慮重新考慮您的設計:

但我會重新考慮你的設計,因為你在這里違反了里氏替換規則。

這是重新設計的嘗試。如果您僅訪問與該特定實例關聯的變量,則無需將父對象傳遞到該方法中。如果您想訪問另一個 Parent 對象,則必須將 Parent 參數添加回方法中。


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

? ? }

}


查看完整回答
反對 回復 2023-09-24
?
撒科打諢

TA貢獻1934條經驗 獲得超2個贊

作為一個抽象類,您可能希望避免處理子對象實例。與前面的答案一樣,嘗試在子級中重寫該方法,并且您可以使用“base”關鍵字調用基類功能。在 VS 中,當您重寫時,它會自動注入該基本調用作為默認語法。



查看完整回答
反對 回復 2023-09-24
  • 2 回答
  • 0 關注
  • 135 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號