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

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)語法。
- 2 回答
- 0 關(guān)注
- 133 瀏覽
添加回答
舉報(bào)