簡體   English   中英

我可以調用基於 class 的 static 方法,並參考實現該基礎 ZA2F2ED4F8EBC2CBB4C21 的 class 嗎?

[英]Can I call a static method that lives on a base class with a reference the the class implementing that base class (in C#)?

我很難說出這個問題,這也讓我很難尋找答案。

這是一個模仿我想做的人為場景:

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

如果您將 Writeline 更改為

Console.WriteLine(BaseClass<T>.MyPropertyName());

你會得到你想要的

為什么在基礎 class 中使用 static function 來檢索有關派生 ZA2F2ED4F8EBC2CBB4DC21A29 的信息? 在任何情況下,您都可以實現成員 function 來包裝 static 調用:

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)) {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM