EDIT:
我已经取出了每个类的代码主体 - 如果您想查看我的答案,请查看编辑修订版:)
首先我们定义界面 http://msdn.microsoft.com/en-us/library/ms173156.aspx
public interface IAnimal
{
string WhatAmI { get; }
string WhatIsMyName { get; }
}
任何实现此接口的类都必须实现这些属性。接口就像一个契约;实现接口的类同意提供接口的方法、属性事件或索引器的实现。
接下来,我们需要定义您的抽象 Animal 类
public abstract class Animal : IAnimal
{
//Removed for Training, See Edit for the code
}
事实上,该类是abstract http://msdn.microsoft.com/en-us/library/sf985hc5(VS.71).aspx指示该类仅作为其他类的基类。我们已经实现了接口的两个属性,并且还有一个私有字段来存储动物名称。此外,我们还做了WhatAmI
属性访问器抽象,以便我们可以在每个派生类中实现我们自己的特定属性访问器逻辑,并且还定义了一个接受字符串参数并将值分配给_name
私人领域。
现在,让我们定义我们的Cat
and Dog
classes
public class Dog : Animal
{
//Removed for Training, See Edit for the code
}
public class Cat : Animal
{
//Removed for Training, See Edit for the code
}
这两个类都继承自Animal
每个都有一个构造函数,它定义一个字符串参数并将该参数作为参数传递给基本构造函数。此外,每个类都实现了自己的属性访问器WhatAmI
,分别返回其类型的字符串。
对于其余的代码
public class Program
{
public static void DescribeAnimal(IAnimal animal)
{
Console.WriteLine("My name is {0}, I am a {1}", animal.WhatIsMyName, animal.WhatAmI);
}
static void Main(string[] args)
{
Dog mydog = new Dog("Spot");
Cat mycat = new Cat("Felix");
DescribeAnimal(mydog);
DescribeAnimal(mycat);
Console.ReadKey();
}
}
静态方法DescribeAnimal
接受一个IAnimal
作为参数并写出返回的值WhatIsMyName
and WhatAmI
传入的属性访问器IAnimal
.
Since Animal
实施IAnimal
以及两者Dog
and Cat
继承自Animal
, any Cat
or Dog
对象可以作为参数传递给DescribeAnimal
method.
我希望我已经清楚地解释了这一点,如果有人觉得我的措辞需要收紧,请发表评论,我将很乐意编辑我的答案。