问题1:
c#接口两种实现方式:
// 直接实现接口
interface IAttack
{
void Attck();
}
class Gun : IAttack
{
public void Attck()
{
throw new NotImplementedException();
}
}
class Rifle : IAttack
{
public void Attck()
{
throw new NotImplementedException();
}
}
// 显示实现接口(当多个接口的中需要实现的方法名称一样的时候)
interface IAttack
{
void Attack();
}
interface ISpecialAttack
{
void Attack();
}
class Gun : IAttack, ISpecialAttack
{
public void Attack()
{
Console.WriteLine("普通攻击");
throw new NotImplementedException();
}
void ISpecialAttack.Attack() // 接口的显示实现
{
Console.WriteLine("特殊攻击");
throw new NotImplementedException();
}
}
class Rifle : IAttack, ISpecialAttack
{
public void Attack()
{
Console.WriteLine("普通攻击");
throw new NotImplementedException();
}
void ISpecialAttack.Attack() // 接口的显示实现
{
Console.WriteLine("特殊攻击");
throw new NotImplementedException();
}
}
public class TestWeapons
{
public void TestMethod()
{
ISpecialAttack desertEagle = new Gun();
desertEagle.Attack();
IAttack rifle = new Rifle();
rifle.Attack();
}
}
c#抽象类定义以及实现:
abstract class Weapon{
public float attackRange;
public float damage;
public virtual void Attack(Enemy enmey)
{
enmey.health -= damage;
Console.WriteLine("attack...");
}
}
class Gun: Weapon
{
public override void Attack(Enemy enmey)
{
base.Attack(enmey);
}
}
public class TestWeapon02
{
public static void main02(string[] args)
{
Enemy enemy = new Enemy();
Weapon gun = new Gun()
{
damage = 5,
attackRange = 100,
};
gun.Attack(enemy);
Console.WriteLine("enemy health: " + enemy.health);
}
}
问题2:
总的来说,抽象类就是类别上的总称;接口就是行为上的规范
展开