源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

c#类的使用示例

  • 时间:2021-01-09 10:22 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:c#类的使用示例
Notes: 数据private类型,大部分方法public类型; 如果有继承或者相互引用,注意数据的公有还是私有,保证数据的只读性质; C#不能够像C++一样在数据声明时调用构造函数,必须使用Myclass temp = new Myclass()来调用构造函数; C#不支持多重继承关系, 也就是说,一个派生类不允许有多个基类。简单点就是,父亲可能有好多儿子(父类可以派生出许多子类),但是一个孩子只能有一个爸爸(子类不允许多重继承关系); C#和其他面向对象一样,重载,多态,虚函数,抽象类这些特性都有; 重载和C++中的重载毫无区别,只有一个问题是在重载大小比较运算符(<, >=, >, <=, ==, !=)的时候,必须成对的重载; 虚函数需加virtual声明,派生类中需要重写,并且添加override声明; 抽象函数需加abstract声明,并且基类中没有执行代码,只能在继承类中添加; 如果需要传出多个值,需要用到ref声明或out声明; ref声明的对象必须提前初始化; out声明的对象不需要提前初始化; 如果类中有静态对象,可以使用静态构造函数对静态对象进行赋值操作。 Example: ElemType.cs
[u]复制代码[/u] 代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test_Class {     class ElementType     {         private int value;         public ElementType() { value = 0; }         public ElementType(int _v)         {             this.value = _v;         }         public void disp()         {             Console.WriteLine("value is {0}", value);         }         public void edit(int _v)         {             this.value = _v;         }         public int reff()         {             return this.value;         }     }     class package     {         private ElementType x;         private ElementType y;         public package()         {             this.x = new ElementType();             this.y = new ElementType();         }         /// <summary>         /// 构造函数         /// </summary>         /// <param name="_x">x</param>         /// <param name="_y">y</param>         public package(int _x, int _y)         {             this.x = new ElementType(_x);             this.y = new ElementType(_y);         }         public void disp()         {             Console.WriteLine("package display");             Console.WriteLine("\tx vaule is {0}", this.x.reff());             Console.WriteLine("\ty vaule is {0}", this.y.reff());             Console.WriteLine();         }         /// <summary>         /// 修改值         /// </summary>         /// <param name="_x">x</param>         /// <param name="_y">y</param>         public void modify(int _x, int _y)         {             this.x.edit(_x);             this.y.edit(_y);         }         public void copyto(ref package p)         {             p.modify(this.x.reff(), this.y.reff());         }     } }
Program.cs
[u]复制代码[/u] 代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test_Class {     class Program     {         static void Main(string[] args)         {             package p1 = new package(5, 5);             package p0 = new package();             p0.disp();             p1.disp();             p1.copyto(ref p0);             p0.disp();             p0.modify(10, 50);             p0.disp();             Console.ReadLine();         }     } }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部