2017-01-12 52 views
0

擴展方法當然可用於將方法添加到您不屬於的類。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:靜態類型不能用作退貨類型「

你能幫我解決這個問題嗎?

+0

「我得到一個錯誤」從來沒有說過有用的東西。是*具體* - 你收到什麼錯誤? –

+0

另外,你說過你想添加一個void方法 - 那麼爲什麼在你嘗試定義一個返回'Dog'的方法呢? –

+0

我得到的錯誤是「狗:靜態類型不能用作參數」 –

回答

1

你需要讓你的Dog類非靜態和參數添加到Jump並返回它:

public class Dog { ... } 

public static class SomeOtherClass 
{ 
    //extension method to the Dog class 
    public static Dog Jump(this Dog dog) 
    { 
     Console.WriteLine("Dog Jumped"); 
     return dog; 
    } 
} 
+0

我試過這個。但是仍然會得到相同的錯誤,並在'跳轉' –

+0

@ Baba.S下面出現一條波浪線 - 錯誤說的是什麼? – Lee

+0

這是因爲你的'Dog'類是'static'。從這個類中移除'static'關鍵字。 – Bidou

4

有一些問題:

  1. 如果你想不返回任何內容的方法,請不要寫出返回的方法Dog
public static Dog Jump(this Dog) 
--------------^^^ 
public static void Jump(this Dog) 
  • Dog類型的參數沒有名稱:
  • public static void Jump(this Dog) 
    ------------------------------^^^ 
    public static void Jump(this Dog dog) 
    
  • 最重要的是:
    擴展方法只是某種「語法糖」,因此您可以編寫myDog.Jump();而不是SomeOtherClass.Jump(myDog);
    這意味着您需要傳遞給擴展方法的類的實例。您不能在類別(例如Dog.Jump();)上調用擴展方法,但只能在對象(例如myDog.Jump();)上調用擴展方法。這就是擴展方法的工作原理。
    此外,你的類Dog是靜態的,這意味着你不能創建它的一個實例,所以你將無法調用Dog myDog = new Dog();,因此將無法調用它的擴展方法。