我正在尋找在(抽象)基類中提供方法的最佳方法,所有繼承類都應該能夠使用它。
該方法需要參考繼承型別的欄位和屬性。
有沒有辦法提供這樣一個原型方法,它不需要我:
- 傳遞對每個有問題的繼承實體的參考
- 在每個繼承類上實作一個方法,該方法將自身的參考傳遞給基類的方法
- 撰寫實作類的擴展方法
以上所有作業,但以自己的方式似乎有些不方便和不優雅。
這是一個示例,其中我實作了上述三種參考繼承類的方法:
using System;
namespace Test
{
public abstract class BaseClass
{
public void ReferenceInheriting(object InheritingInstance)
{
Console.WriteLine("Do things specific to the inheriting class or instance thereof: " InheritingInstance.GetType().Name);
}
}
public class Inheriting : BaseClass
{
public void MakeUseOfBaseClassImplementation()
{
base.ReferenceInheriting(this);
}
}
public static class Extensions
{
public static void BeAvailableForAllImplementing(this BaseClass Inh)
{
Console.WriteLine("Do things specific to the inheriting class or instance thereof: " Inh.GetType().Name);
}
}
class program
{
public static void Main(string[] args)
{
Inheriting inh = new Inheriting();
Console.WriteLine("Method 1: Calling the inherited method from an inheriting instance, passing a reference to the instance:");
inh.ReferenceInheriting(inh);
Console.WriteLine("Method 2: Implementing call to the base class's method in own class:");
inh.MakeUseOfBaseClassImplementation();
Console.WriteLine("Method 3: Extension method for all implementing classes:");
inh.BeAvailableForAllImplementing();
}
}
}
這三種方法都產生相同的輸出,但都有缺點。
缺少決議呼叫者資訊,是否有另一種方法可以做到這一點?
這當然不是什么大問題,但我有興趣使這種方法盡可能地用戶友好,無論是實作繼承還是呼叫。
謝謝!
uj5u.com熱心網友回復:
你不需要任何這些。
這個:
public void reflectInheriting(object inheritingInstance)
{
Console.WriteLine("Do things specific to the inheriting class or instance thereof: " inheritingInstance.GetType().Name);
FieldInfo fi = inheritingInstance.GetType().GetField("getMe");
Console.WriteLine(fi.GetValue(inheritingInstance));
}
可以簡單地改寫為:
public void reflectInheriting()
{
Console.WriteLine("Do things specific to the inheriting class or instance thereof: " this.GetType().Name);
FieldInfo fi = this.GetType().GetField("getMe");
Console.WriteLine(fi.GetValue(this));
}
這就是你所需要的。
C#不管它是如何的演員,所以即使里面保存了實際的基礎類的一個物件BaseClass,this.GetType()將是Inheriting。
程式輸出證明沒有任何改變:
方法一:從繼承實體呼叫繼承方法,傳遞對實體的參考:
做特定于繼承類或其實體的事情:繼承
在 BaseClass 中使用我
方法二:在自己的類中實作對基類方法的呼叫:
做特定于繼承類或其實體的事情:
繼承在 BaseClass 中使用我
方法三:所有實作類的擴展方法:
做特定于繼承類或其實體的事情:繼承
在 BaseClass 中使用我
uj5u.com熱心網友回復:
您可以使用反射,但那是一種不得已的武器。訪問派生類中的屬性或方法的慣用方式是在基類中使其抽象。
public abstract class BaseClass
{
public void GetInheriting()
{
Console.WriteLine("GetMe is: {0}", this.GetMe);
}
protected abstract string GetMe { get; }
}
public class Inheriting : BaseClass
{
protected override string GetMe => "Use me in BaseClass";
public void MakeUseOfBaseClassImplementation()
{
base.GetInheriting();
}
}
public class Program
{
static public void Main()
{
var o = new Inheriting();
o.MakeUseOfBaseClassImplementation();
}
}
鏈接到小提琴
輸出:
GetMe is: Use me in BaseClass
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314647.html
上一篇:PythonOOB:不理解子類
下一篇:我如何分組此資料表上的一列
