static class PetGuide
{
static public void HowToFeedDog(this Dog dog)
{
Console.WriteLine("Play a video about how to feed a dog.");
}
}
HowToFeedDog提示:扩展方法必须在顶级静态类中定义;PetGuide是嵌套类
运行语句Dog dog=new Dog("Tommy");
dog.后没有出现HowToFeedDog
前面的代码目前没有出现错误,感谢回答!
嵌套类,这个是一个内部类,所以无法访问。可能是没注意相关括号的作用域,仔细检查一下。把他定义在外面。
我也遇到了,需要把类直接放在 class Program{}的外面,然后通过智能提示补全dog类的引用就可以了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
//结构
struct fish {
int size;
int weight;
int type;
}
interface jieko{
void chatchMoutc();//接口中默认是public,但不能加修饰符,且也不能在接口中实现
}
interface upTree {
void upTrees();
}
static void Main(string[] args)
{
pet[] pets = new pet[] { new dog("小黑"),new cat("小密"),new dog("大黄"), };
for (var i =0;i<pets.Length;i++) {
pets[i].spicking();
}
dog dog1 = new dog("小九");
dog1.PetGuide();
dog.showDogNume();
//pet dog = new dog();
//dog._name = "小黑";
//dog.printName();
//pet cat = new cat();
//cat._name = "小密";
//cat.printName();
//dog.spicking();
//cat.spicking();
cat cat = new cat("小密");
upTree utree = cat;
cat.upTrees();
utree.upTrees();
jieko chatct = cat;
cat.chatchMoutc();
chatct.chatchMoutc();
Console.ReadKey();
}
abstract public class pet{
protected string _name;
public pet(string Name)
{
_name = Name;
}
public void printName() {
Console.WriteLine("动物的名字叫"+_name);
}
//虚方法
//virtual public void spicking() {
// Console.WriteLine("动物说话了");
//}
//抽象方法 必须放在抽象类里面
abstract public void spicking();
}
public class dog :pet{
static int Num;
static dog() {
Num = 0;
}
public dog(string Name) : base(Name)
{
++Num;
}
new public void printName()
{
Console.WriteLine("小动物的名字叫" + _name);
}
sealed override public void spicking()
{
Console.WriteLine(_name +"说:汪汪汪");
}
static public void showDogNume() {
Console.WriteLine("目前有"+Num+"条狗");
}
}
public class cat : pet,upTree, jieko //在类中实现了接口,也需要实现接口中的方法
{
public cat(string Name) : base(Name)
{
}
new public void printName()
{
Console.WriteLine("小动物的名字叫" + _name);
}
public override void spicking()
{
Console.WriteLine(_name + "说:喵喵喵");
}
public void upTrees() {
Console.WriteLine(_name + "爬树");
}
public void chatchMoutc() {
Console.WriteLine(_name + "抓老鼠");
}
}
}
static class showVideo
{
static public void PetGuide(this Program.dog dog)
{
Console.WriteLine("播放视频");
}
}
}
把PetGuide定义到namespace下面试试吧