我很難表達這個問題,這也讓我很難找到答案。
這是一個模仿我想做的人為的場景:
void Main()
{
Console.WriteLine(TestClassA.MyPropertyName());
Console.WriteLine(TestClassB.MyPropertyName());
var speaker = new TestSpeaker();
speaker.Speak<TestClassA>();
speaker.Speak<TestClassB>();
}
public class TestSpeaker {
public void Speak<T>() where T : BaseClass<T> {
Console.WriteLine(/* I want to call T.MyPropertyName() here */);
}
}
public class TestClassA : BaseClass<TestClassA> {
public string Name { get; set; }
}
public class TestClassB : BaseClass<TestClassB> {
public string OtherPropertyName { get; set; }
}
public abstract class BaseClass<T> {
public static string MyPropertyName(){
return typeof(T).GetProperties().Single().Name;
}
}
控制臺現在會顯示:
Name
OtherPropertyName
我想替換我注釋掉的代碼,使其顯示為:
Name
OtherPropertyName
Name
OtherPropertyName
uj5u.com熱心網友回復:
如果您將 Writeline 更改為
Console.WriteLine(BaseClass<T>.MyPropertyName());
你會得到你想要的
uj5u.com熱心網友回復:
為什么在基類中使用靜態函式來檢索有關派生類的資訊?在任何情況下,您都可以實作一個成員函式來包裝靜態呼叫:
public static string MyStaticFunction() => return "whatever";
public string MyMemberFunction() => MyStaticFunction();
但在您的場景中,也許您應該簡單地宣告一個抽象屬性(或函式),用于回傳您要查找的值并在派生類中覆寫它:
根據:
public abstract string MyPropertyName { get; }
衍生的:
public override string MyPropertyName => nameof(OtherPropertyName); // or more complex logic
另一種可能的解決方案是將資訊作為字串(或屬性運算式,如果您愿意的話)傳遞給基類的建構式:
根據:
public string MyPropertyName { get; init; }
public BaseClass(string propertyName)
{
MyPropertyName = propertyName; // maybe validate that the property exists
}
衍生的:
public MyTestClassB() : BaseClass(nameof(OtherPropertyName)) {}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/366532.html
