欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#类的使用示例

程序员文章站 2024-02-22 13:29:10
notes:数据private类型,大部分方法public类型; 如果有继承或者相互引用,注意数据的公有还是私有,保证数据的只读性质; c#不能够像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();
        }
    }
}