实现接口 [英] Implementing the Interface
本文介绍了实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码完全来自书籍示例。但仍然给我错误。我无法弄清楚出了什么问题。书也给出了输出:宝贝叫:小猫和宝贝叫:小狗。我很难理解界面,最重要的是本书的例子给我错误,任何帮助都将非常感激。
{
interface ILiveBirth
{
string BabyCalled();
}
class Animal {}
class Cat:Animal, ILiveBirth
{
string ILiveBirth.BabyCalled()
{ return kitten; }
}
class 狗:动物,ILiveBirth
{
string ILiveBirth.BabyCalled()
{ return 小狗跨度>; }
}
class Bird:Animal
{}
类计划
{
静态 void Main()
{
Animal [] animalArray = new 动物[ 3 ];
animalArray [ 0 ] = new Cat();
animalArray [ 1 ] = new Bird();
animalArray [ 2 ] = new Dog();
foreach (Animal a in animalArray)
{
ILiveBirth b = ILiveBirth;
if (b!= null )
Console.WriteLine( Baby被称为:{0},b.Babycalled());
}
}
}
}
解决方案
以下代码行中有几个错误:
if (b != null )
Console.WriteLine( Baby被称为:{0},b。 Babycalled ());
1.应该是!=
,而不是! =
(没有空格)。
2.应该是BabyCalled
,而不是Babycalled
(区分大小写)。
正确版本:
if (b != null )
Console.WriteLine( Baby被称为:{0},b。 BabyCalled ());
Below codes are exactly from book example. But still giving me errors. I couldn't figure out what is wrong. Book also gave the output: Baby is called: kitten and Baby is called: puppy. I have hard time understanding the interface, on top of that this book example is giving me error, any help will be very appreciated.
{
interface ILiveBirth
{
string BabyCalled();
}
class Animal { }
class Cat : Animal, ILiveBirth
{
string ILiveBirth.BabyCalled()
{ return "kitten"; }
}
class Dog : Animal, ILiveBirth
{
string ILiveBirth.BabyCalled()
{ return "puppy"; }
}
class Bird : Animal
{ }
class Program
{
static void Main()
{
Animal[] animalArray = new Animal[3];
animalArray[0] = new Cat();
animalArray[1] = new Bird();
animalArray[2] = new Dog();
foreach(Animal a in animalArray)
{
ILiveBirth b = a as ILiveBirth;
if (b ! = null)
Console.WriteLine("Baby is called:{0}", b.Babycalled());
}
}
}
}
解决方案
Hi,
There are a couple of errors in the following lines of code:
if (b ! = null) Console.WriteLine("Baby is called:{0}", b.Babycalled());
1. Should be!=
, not! =
(without a space).
2. Should beBabyCalled
, notBabycalled
(case sensitivity).
Correct version:
if (b != null) Console.WriteLine("Baby is called:{0}", b.BabyCalled());
这篇关于实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文