热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

c#面向对象/继承关系设计

继承RTTIRTTI概念RTTI(RunTimeTypeIdentification)即通过运行时类型识别,程序能够使用基类的指针或引用来检查着这些指针或引用所指的对象的实际派生类

继承

RTTI


RTTI

概念 RTTI(Run Time Type Identification)即通过运行时类型识别,程序能够使用基类的指针或引用来检查着这些指针或引用所指的对象的实际派生类型。



相关资源

C#高级编程(第11版) Professional C# 7 and .NET Core 2.0

For code comments and issues please check Professional C#'s GitHub Repository

Please check my blog csharp.christiannagel.com for additional information for topics covered in the book.

在ObjectOrientation 章节中有介绍,

但是有些内容没有细讲, 比如纯虚函数的子类如何 在全局变量声明,如何在函数中定义,使用



c#

父类,子类



1.VirtualMethods


// fish tail, lungs
// humam limbs(arms and legs), lungs
// bird wings, lungs
//
public abstract class Organisms
{
public Int32 age{get;}
public virtual void GetAge()
{
WriteLine($"moves with {limbs}");
}

public abstract void Move( );
}
public class Human: Organisms
{
public Human()
: base() { }
public override void Move( ) // must override
{
WriteLine($"Human: moves with legs (using limbs when baby age)");
}
}
public class Kingkong: Organisms
{
public Human()
: base() { }
public override void Move( ) // must override
{
WriteLine($"Kingkong: moves with limbs");
}
}
public class Fish: Organisms
{
public Fish()
: base() { }
public override void Move( ) // must override
{
WriteLine($"Fish: moves with wings and tail");
}
}
public class Horse: Organisms //horse zebra
{
public Horse()
: base() { }
public override void Move( ) // must override
{
WriteLine($"Horse: moves with legs");
}
}

using System;
namespace VirtualMethods
{
class Program
{
//var _obj = null; //var 无法在全局变量 声明
Organisms _Obj =null;
static void Main()
{
var obj = new Human();
obj.age = 23;
obj.GetAge();
obj.Move();

}
static void Init()
{
_Obj = new Fish();
_Obj.age = 2;
_Obj.GetAge();
_Obj.Move();//父类有abstract function. 所有子类函数必须override,
}

static void FuncA()
{
Fish fish = _Obj as Fish;//利用全局变量 _Obj
fish.age = 1;
fish.GetAge();
fish.Move();
}

}
}




2.InheritanceWithConstructors

//Shape.cs
using System;
namespace InheritanceWithConstructors
{
public class Position
{
public int X { get; set; }
public int Y { get; set; }
public override string ToString() => $"X: {X}, Y: {Y}";
}
public class Size
{
public int Width { get; set; }
public int Height { get; set; }
public override string ToString() => $"Width: {Width}, Height: {Height}";
}
public class Shape
{
public Shape(int width, int height, int x, int y)
{
Size = new Size { Width = width, Height = height };
Position = new Position { X = x, Y = y };
}
public Position Position { get; }
public Size Size { get; }
public virtual void Draw() => Console.WriteLine($"Shape with {Position} and {Size}");
public virtual void Move(Position newPosition)
{
Position.X = newPosition.X;
Position.Y = newPosition.Y;
Console.WriteLine($"moves to {Position}");
}
}
}

//ConcreteShapes.cs
using System;
namespace InheritanceWithConstructors
{
public class Rectangle : Shape
{
public Rectangle(int width, int height, int x, int y)
: base(width, height, x, y) { }
public Rectangle()
: base(width: 0, height: 0, x: 0, y: 0) { }
public override void Draw() =>
Console.WriteLine($"Rectangle with {Position} and {Size}");
public override void Move(Position newPosition)
{
Console.Write("Rectangle ");
base.Move(newPosition);
}

public void PrintRectangleFuncA( )//只有Rectangle 才有的函数,其他类没有声明和实现
{
Console.Write("Rectangle FuncA ");
}
}
public class Ellipse : Shape
{
public Ellipse(int width, int height, int x, int y)
: base(width, height, x, y) { }
public Ellipse()
: base(width: 0, height: 0, x: 0, y: 0) { }
}
}

//Program.cs
namespace InheritanceWithConstructors
{
class Program
{
Shape _sharp = null;//全局变量
static void Main(string[] args)
{
var r = new Rectangle();
r.Position.X = 33;
r.Position.Y = 22;
r.Size.Width = 200;
r.Size.Height = 100;
r.Draw();
DrawShape(r);
r.Move(new Position { X = 120, Y = 40 });
r.Draw();
Shape s1 = new Ellipse();
DrawShape(s1);
}
public staic void Init()
{
_sharp = new Rectangle();//如果_sharp 是全局变量, 让其他地方也可使用此对象 怎么办?
}
public staic void FuncA()
{
Rectangle rect= _sharp as Rectangle;
rect.PrintRectangleFuncA(); //只有Rectangle 才有的函数,其他类没有声明和实现,可以这样调用
}
public static void DrawShape(Shape shape) => shape.Draw();
}
}




3.UsingInterfaces

//基本上和VirtualMethods 类似,但是所有接口类的 子类, 要通用, 子类必须

//IBankAccount.cs
namespace Wrox.ProCSharp
{
public interface IBankAccount
{
void PayIn(decimal amount);//子类必须有实现
bool Withdraw(decimal amount);//子类必须有实现
decimal Balance { get; }//子类必须有实现
}
}

//ITransferBankAccount.cs
namespace Wrox.ProCSharp
{
public interface ITransferBankAccount : IBankAccount
{
bool TransferTo(IBankAccount destination, decimal amount);
}
}

//JupiterBank.cs
using System;
namespace Wrox.ProCSharp.JupiterBank
{
public class GoldAccount : IBankAccount
{
private decimal _balance;
public void PayIn(decimal amount) => _balance += amount;
public bool Withdraw(decimal amount)//Withdraw撤回
{
if (_balance >= amount)
{
Console.WriteLine($"GoldAccount(IBankAccount): Withdraw(){_balance}");
_balance -= amount;
return true;
}
Console.WriteLine("GoldAccount(IBankAccount): Withdraw attempt failed.");
return false;
}
public decimal Balance => _balance;
public override string ToString() =>
$"GoldAccount(IBankAccount): Balance = {_balance,6:C}";
}
public class CurrentAccount : ITransferBankAccount
{
private decimal _balance;
public void PayIn(decimal amount) => _balance += amount;
public bool Withdraw(decimal amount)
{
if (_balance >= amount)
{
_balance -= amount;
return true;
}
Console.WriteLine("Withdrawal attempt failed.");
return false;
}
public decimal Balance => _balance;
public bool TransferTo(IBankAccount destination, decimal amount)
{
bool result = Withdraw(amount);
if (result)
{
destination.PayIn(amount);
}
return result;
}
public override string ToString() =>
$"Jupiter Bank Current Account: Balance = {_balance,6:C}";
}
}

//VenusBank.cs
using System;
namespace Wrox.ProCSharp.VenusBank
{
public class SaverAccount : IBankAccount
{
private decimal _balance;
public void PayIn(decimal amount) => _balance += amount;
public bool Withdraw(decimal amount)
{
if (_balance >= amount)
{
_balance -= amount;
return true;
}
Console.WriteLine("Withdrawal attempt failed.");
return false;
}
public decimal Balance => _balance;
public override string ToString() =>
$"Venus Bank Saver: Balance = {_balance,6:C}";
}
}

//Program.cs
namespace UsingInterfaces
{
class Program
{
IBankAccount _golbal_obj =null;//全局变量
static void Main()
{
IBankAccount venusAccount = new SaverAccount();
IBankAccount jupiterAccount = new GoldAccount();
venusAccount.PayIn(200);
venusAccount.Withdraw(100);
Console.WriteLine(venusAccount.ToString());
jupiterAccount.PayIn(500);
jupiterAccount.Withdraw(600);
jupiterAccount.Withdraw(100);
Console.WriteLine(jupiterAccount.ToString());

}

public static void Init()
{
_golbal_obj = new SaverAccount();//用子类去new
}
public static void FunA()
{
if(_golbal_obj!=null)
{
_golbal_obj.PayIn(100);//直接调用SaverAccount 子类的 实现,所以这也是为什么需要子类全部都要实现,
_golbal_obj.Withdraw(100);//直接调用SaverAccount 子类的 实现
}
}


}
}


推荐阅读
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • C# 7.0 新特性:基于Tuple的“多”返回值方法
    本文介绍了C# 7.0中基于Tuple的“多”返回值方法的使用。通过对C# 6.0及更早版本的做法进行回顾,提出了问题:如何使一个方法可返回多个返回值。然后详细介绍了C# 7.0中使用Tuple的写法,并给出了示例代码。最后,总结了该新特性的优点。 ... [详细]
  • 本文介绍了Java高并发程序设计中线程安全的概念与synchronized关键字的使用。通过一个计数器的例子,演示了多线程同时对变量进行累加操作时可能出现的问题。最终值会小于预期的原因是因为两个线程同时对变量进行写入时,其中一个线程的结果会覆盖另一个线程的结果。为了解决这个问题,可以使用synchronized关键字来保证线程安全。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
author-avatar
fseiei
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有