[英]C# accessors and object class inheritance
所以我對對象繼承和構造函數有一個天真的問題。 基本上,一個類具有一個對象:
public class ParentClass{
protected Parent item;
訪問器如下:
public Parent ItemValue
{
set
{
item = value;
}
get
{
return item;
}
}
現在,我想繼承該類:
public class ChildClass:ParentClass
{
public new Child item;
}
現在,每當我通過繼承的訪問器訪問Child item
時,它當然都將其作為Parent
類而不是Child
類返回。 有沒有一種方法可以使其在不覆蓋ChildClass
的訪問器的情況下將item
作為Child
類返回?
不,您不能將基本屬性的類型更改為返回不同的(派生的)類型。
如果不需要繼承,則采用標准解決方法-通用類:
public class ParentClass<T> {
public T ItemValue { get; set; }
...
}
public class ChildClass : ParentClass<ChildClass>
{
...
}
請注意,如果您只需要訪問其自己類中的項目,則可以擁有virtual
屬性:
public class Parent { }
public class Child:Parent { public string ChildProperty; }
public abstract class ParentClass
{
public abstract Parent ItemValue { get; }
}
public class ChildClass : ParentClass
{
Child item;
public override Parent ItemValue { get {return item;} }
public void Method()
{
// use item's child class properties
Console.Write(item.ChildProperty);
}
}
如果您只是想讓您的后代類定義類型的Item,則可以執行此操作
public class ParentClass<T>{
protected T item;
public T ItemValue
{
set
{
item = value;
}
get
{
return item;
}
}
}
public class ChildClass:ParentClass<Child>
{
// No need to create a new definition of item
}
但是,根據您的問題,下一個問題將是當它們具有不同的T時,如何將ChildClass1和ChildClass2添加到相同的List / Array / Dictionary / etc。
退后一分鍾。 您的ParentClass真的需要知道是什么嗎?
(Ab)使用上面的Animal示例,您的Horse可能具有Walk(),Trot(),Canter()或Gallop()方法,而Duck可能具有Swim()或Waddle()方法。
也許您的邏輯是這樣說的,重復我的動物收藏並告訴游泳者游泳。 在這種情況下,您可以聲明:
using System;
using System.Collections.Generic;
public class Program
{
public class Location {}
public interface ISwimmer{
void SwimTo(Location destination);
}
public class Animal {} // whatever base class properties you need
public class Duck : Animal, ISwimmer
{
public void SwimTo(Location destination)
{
Console.WriteLine("Implement duck's swim logic");
}
}
public class Fish : Animal, ISwimmer
{
public void SwimTo(Location destination)
{
Console.WriteLine("Implement fish's swim logic");
}
}
public class Giraffe : Animal {}
public static void Main()
{
List<Animal> animals = new List<Animal>
{
new Duck(),
new Fish(),
new Giraffe()
};
foreach (Animal animal in animals)
{
ISwimmer swimmer = animal as ISwimmer;
if (swimmer==null) continue; // this one can't swim
swimmer.SwimTo(new Location());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.