c#认证题(2)
本题设计到了属性,虚方法,继承与派生,还有多态,这里我简单的写下属性的设置
1.C#属性:
(1) 属性(Property) 是类(class)、结构(structure)和接口(interface)的命名(named)成员。类或结构中的成员变量或方法称为 域(Field)。属性(Property)是域(Field)的扩展,且可使用相同的语法来访问。它们使用 访问器(accessors) 让私有域的值可被读写或操作。
属性(Property)不会确定存储位置。相反,它们具有可读写或计算它们值的 访问器(accessors)
(2)访问器:属性(Property)的访问器(accessor)包含有助于获取(读取或计算)或设置(写入)属性的可执行语句。访问器(accessor)声明可包含一个 get 访问器、一个 set 访问器,或者同时包含二者。(摘自菜鸟教程)
eg: public class Anima
{ private string sex;
public string Sex
{ set{sex=vaule;}
get{return sex;}
}
}
c#通过属性特性读取和写入字段,而不直接读取和写入,以此来提供对类中字段的保护.
using System;
using System.Collections.Generic;
using System.Linq; using System.Text;
using System.Threading.Tasks;
namespace Test2_1
{ class Animal
{ private bool m_sex;
private int m_age;
public Animal()
{
m_sex = false; }
public bool Sex
{ set { m_sex = value; }
get { return m_sex; }
}
public int Age
{ set { m_age = value; }
get { return m_age; }
}
public virtual void Introduce()
{ if (Sex == true)
Console.WriteLine("This is a male Animal");
else
Console.WriteLine("This is a fmale Animal");
}
}
class Dog : Animal
{ public Dog()
{ Sex=true; } p
ublic override void Introduce()
{ if (Sex == true)
Console.WriteLine("This is a male Dog");
else
Console.WriteLine("This is a fmale Dog");
} }
class Cat : Animal
{ public override void Introduce()
{ if (Sex == true)
Console.WriteLine("This is a male Cat");
else
Console.WriteLine("This is a fmale Cat");
} }
}
namespace Test2_1
{
class Program
{
static void Main(string[] args)
{
Animal ani = new Animal();
Dog dog = new Dog();
Cat cat = new Cat();
ani.Introduce();
dog.Introduce();
cat.Introduce();
}
}
}
这道题相比上一题用到了抽象方法,作为一名初学者,实在不知道抽象方法的作用在哪,没有实体,只能在派生类里重写,那为何不直接在派生类写方法而要用抽象方法?
以下是在网上找到的关于抽象方法的资料:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test2_11
{
abstract class Animal
{
private bool m_sex;
private string m_sound;
public bool Sex
{
set { m_sex = value; }
get { return m_sex; }
}
public string Sound
{
set { m_sound = value; }
get { return m_sound; }
}
public Animal()
{ m_sex=true;
m_sound = "How1...";
}
public abstract string Roar();
}
class Dog : Animal
{
public Dog()
{ Sex=true;
Sound = "Wow...";
}
public override string Roar()
{
return ("Dog is speaking:" + Sound);
}
}
class Cat: Animal
{
public Cat()
{
Sound = "Miaow...";
}
public override string Roar()
{
return ("Cat is speaking:" + Sound);
}
}
class Cow: Animal
{
public Cow()
{
Sound = "Moo...";
}
public override string Roar()
{
return ("Cow is speaking:" + Sound);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test2_11
{
class Program
{
static void Main(string[] args)
{
Animal animal;
animal= new Dog();
Console.WriteLine(animal.Roar());
animal = new Cat();
Console.WriteLine(animal.Roar());
animal = new Cow();
Console.WriteLine(animal.Roar());
}
}
}