c#扩展方法 - 添加void方法

时间:2017-01-12 09:58:30

标签: c# extension-methods static-methods void

扩展方法当然可以用于将方法添加到您不拥有的类中。

但我想在Visual Studio中练习这个概念,但不确定所需的符号。

例如,我有以下课程

public static class Dog
{
    public static void Bark()
    {
        Console.WriteLine("Woof!");
    }
}

让我们假设我不拥有这种方法(我这样做,但让我假装不这样做)。我如何使用名为Jump的新方法(在本质上为void)扩展类,其中所有新方法将打印到Dog跳跃的控制台?

我试图使用以下方法添加:

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

然而,我收到错误:

  

“狗:静态类型不能用作参数”

  

“狗:静态类型不能用作返回类型”

你能帮我解决一下这个问题吗?

2 个答案:

答案 0 :(得分:5)

有一些问题:

  1. 如果您想要一个不返回任何内容的方法,请不要写一个返回Dog的方法:
  2. public static Dog Jump(this Dog)
    --------------^^^
    public static void Jump(this Dog)
    
    1. 类型Dog的参数没有名称:
    2. public static void Jump(this Dog)
      ------------------------------^^^  
      public static void Jump(this Dog dog)
      
      1. 最重要的是:
        扩展方法只是某种“语法糖”,因此您可以写myDog.Jump();而不是SomeOtherClass.Jump(myDog);
        这意味着您需要传递给扩展方法的类的实例。您无法在(例如Dog.Jump();)上调用扩展方法,但仅限于对象(例如myDog.Jump();)。这就是扩展方法的工作原理 此外,您的班级Dog是静态的,这意味着您无法创建它的实例,因此您将无法调用Dog myDog = new Dog();,因此无法在其上调用扩展方法。< / LI>

答案 1 :(得分: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;
    }
}