擴展方法當然可用於將方法添加到您不屬於的類。c#擴展方法 - 添加一個無效方法
但我想在Visual Studio中練習這個概念,但不確定所需的符號。
例如,我有下面的類
public static class Dog
{
public static void Bark()
{
Console.WriteLine("Woof!");
}
}
假設我並不擁有這個方法(這是我做的,但讓我們假裝我不知道)。我如何着手使用一種新方法(本質上是void)來擴展這個類,這個方法叫做Jump,其中所有的新方法都會在控制檯上打印Dog跳轉的內容。
我試圖這樣使用補充:
public static class SomeOtherClass
{
//extension method to the Dog class
public static Dog Jump(this Dog)
{
Console.WriteLine("Dog Jumped");
}
}
不過,我得到錯誤:
「狗:靜態類型不能用作參數」
和
「Dog:靜態類型不能用作退貨類型「
你能幫我解決這個問題嗎?
「我得到一個錯誤」從來沒有說過有用的東西。是*具體* - 你收到什麼錯誤? –
另外,你說過你想添加一個void方法 - 那麼爲什麼在你嘗試定義一個返回'Dog'的方法呢? –
我得到的錯誤是「狗:靜態類型不能用作參數」 –