多态是同一个行为具有多个不同表现形式或形态的能力,意味着有多重形式。在面向对象编程范式中,多态性往往表现为"一个接口,多个功能"。
在 C# 中,每个类型都是多态的,因为包括用户定义类型在内的所有类型都继承自 Object。
多态性分为静态的和动态多态。在静态多态性中,函数的响应是在编译时发生的。在动态多态性中,函数的响应是在运行时发生的。
class GameObject
{
public string name;
public GameObject(string name)
{
this.name = name;
}
//虚函数 可以被子类重写
public virtual void Atk()
{
Console.WriteLine("游戏对象进行攻击");
}
}
class Player : GameObject
{
public Player(string name) : base(name)//调用父类的构造函数
{
}
//重写虚函数
public override void Atk()
{
Console.WriteLine("玩家对象进行攻击");
}
}
class Monster : GameObject
{
public Monster(string name) : base(name)
{
}
public override void Atk()
{
base.Atk();//base代表父类,可以通过它来保留父类的行为,会调用一次父类的方法
Console.WriteLine("怪物对象进行攻击");
}
}
class Father
{
public void SpeakName()
{
Console.WriteLine("Father的方法");
}
}
class Son : Father
{
public new void SpeakName()
{
Console.WriteLine("Son的方法");
}
}
//Main
//用父类取装载子类的对象时,有两个同名的方法,会优先调用父类的 多态就用来解决这类问题
Father f = new Son();
f.SpeakName();
(f as Son).SpeakName();
GameObject p = new Player("abc");//虚函数和重写解决了问题
p.Atk();
GameObject m = new Monster("def");
m.Atk();
/*
输出:
Father的方法
Son的方法
玩家对象进行攻击
游戏对象进行攻击
怪物对象进行攻击
*/
用 abstract 关键字修饰的类。
特点:
abstract class Thing//抽象一类物品
{
public string name;
//可以在抽象类中写抽象函数
}
class Water : Thing
{
}
用 abstract 修饰的方法,又叫 纯虚方法
特点:
abstract class Fruits
{
public string name;
public virtual void Test()
{
//虚方法可以写逻辑
}
public abstract void Bad();//抽象方法
}
class Apple : Fruits
{
//虚方法在子类中可以选择是否重写
//抽象方法一定要重写
public override void Bad()
{
}
}
关键字:interface,接口是行为的抽象规范,是抽象行为的“基类”,各种类通过继承它来实现对应的行为。
接口声明规范:
接口使用规范:
特点:
/*
interface 接口名
{
}
接口名:I+帕斯卡命名法
*/
interface IFly
{
void Fly();//方法
string Name//属性
{
get;
set;
}
int this[int index]//索引
{
get;
set;
}
event Action doSomething;//事件
}
接口用来继承:
class Animal
{
}
class Tiger : Animal, IFly//继承类和接口
{
//实现接口内容
public void Fly()
{
}
public string Name
{
get;
set;
}
public int this[int index]
{
get
{
return 0;
}
set
{
}
}
public event Action doSomething;
}
interface IWalk
{
void Walk();
}
interface IMove : IFly, IWalk
{
}
class Test : IMove//实现所有内容
{
public int this[int index]
{
get => throw new NotImplementedException(); set => throw new NotImplementedException();
}
public string Name
{
get => throw new NotImplementedException(); set => throw new NotImplementedException();
}
public event Action doSomething;
public void Fly()
{
throw new NotImplementedException();
}
public void Walk()
{
throw new NotImplementedException();
}
}
interface IAtk
{
void Atk();
}
interface ISuperAtk
{
void Atk();
}
class Player : IAtk, ISuperAtk
{
//显示实现接口:接口名.行为名
void IAtk.Atk()
{
}
void ISuperAtk.Atk()
{
}
}
abstract class Animal
{
public string name;
public abstract void Eat();
public virtual void Speak()
{
Console.WriteLine("giao");
}
}
class Person : Animal
{
public override void Eat()
{
}
public override void Speak()
{
}
}
class WhitePerson : Person
{
public sealed override void Eat()//不能重写了
{
base.Eat();
}
public override void Speak()
{
base.Speak();
}
}
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我想让一个yaml对象引用另一个,如下所示:intro:"Hello,dearuser."registration:$introThanksforregistering!new_message:$introYouhaveanewmessage!上面的语法只是它如何工作的一个例子(这也是它在thiscpanmodule中的工作方式。)我正在使用标准的rubyyaml解析器。这可能吗? 最佳答案 一些yaml对象确实引用了其他对象:irb>require'yaml'#=>trueirb>str="hello"#=>"hello"ir
假设我有一个FireNinja我的数据库中的对象,使用单表继承存储。后来才知道他真的是WaterNinja.将他更改为不同的子类的最干净的方法是什么?更好的是,我很想创建一个新的WaterNinja对象并替换旧的FireNinja在数据库中,保留ID。编辑我知道如何创建新的WaterNinja来self现有FireNinja的对象,我也知道我可以删除旧的并保存新的。我想做的是改变现有项目的类别。我是通过创建一个新对象并执行一些ActiveRecord魔法来替换行,还是通过对对象本身做一些疯狂的事情,或者甚至通过删除它并使用相同的ID重新插入来做到这一点,这是问题的一部分。