手机
当前位置:查字典教程网 >编程开发 >C#教程 >c#类的使用示例
c#类的使用示例
摘要:Notes:数据private类型,大部分方法public类型;如果有继承或者相互引用,注意数据的公有还是私有,保证数据的只读性质;C#不能...

Notes:

数据private类型,大部分方法public类型;

如果有继承或者相互引用,注意数据的公有还是私有,保证数据的只读性质;

C#不能够像C++一样在数据声明时调用构造函数,必须使用Myclass temp = new Myclass()来调用构造函数;

C#不支持多重继承关系, 也就是说,一个派生类不允许有多个基类。简单点就是,父亲可能有好多儿子(父类可以派生出许多子类),但是一个孩子只能有一个爸爸(子类不允许多重继承关系);

C#和其他面向对象一样,重载,多态,虚函数,抽象类这些特性都有;

重载和C++中的重载毫无区别,只有一个问题是在重载大小比较运算符(<, >=, >, <=, ==, !=)的时候,必须成对的重载;

虚函数需加virtual声明,派生类中需要重写,并且添加override声明;

抽象函数需加abstract声明,并且基类中没有执行代码,只能在继承类中添加;

如果需要传出多个值,需要用到ref声明或out声明;

ref声明的对象必须提前初始化;

out声明的对象不需要提前初始化;

如果类中有静态对象,可以使用静态构造函数对静态对象进行赋值操作。

Example:

ElemType.cs

复制代码 代码如下:

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

复制代码 代码如下:

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();

}

}

}

【c#类的使用示例】相关文章:

c#剪切板操作的简单实例

C#多维数组学习使用

基于运算符重载的那些事

浅谈C#中Process类的使用详解

C# Dictionary的使用实例代码

C#中HashTable的定义与使用方法

介绍C# 泛型类在使用中约束

浅析C# 基础语法的使用

C#委托初级使用的实例代码

c# 类和成员的修饰详细介绍

精品推荐
分类导航