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

TA貢獻1934條經驗 獲得超2個贊
作為一個抽象類,您可能希望避免處理子對象實例。與前面的答案一樣,嘗試在子級中重寫該方法,并且您可以使用“base”關鍵字調用基類功能。在 VS 中,當您重寫時,它會自動注入該基本調用作為默認語法。
- 2 回答
- 0 關注
- 135 瀏覽
添加回答
舉報