扩展方法当然可以用于将方法添加到您不拥有的类中。
但我想在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");
}
}
然而,我收到错误:
“狗:静态类型不能用作参数”
和
“狗:静态类型不能用作返回类型”
你能帮我解决一下这个问题吗?
答案 0 :(得分:5)
有一些问题:
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();
,因此无法在其上调用扩展方法。< / 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;
}
}