频道栏目
首页 > 资讯 > C# > 正文

c#类的使用规范

18-01-15        来源:[db:作者]  
收藏   我要投稿
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();
        }
        /// 
        /// 构造函数
        /// 
        ///x
        ///y
        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();
        }
        /// 
        /// 修改值
        /// 
        ///x
        ///y
        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();
        }
    }
}

 

相关TAG标签
上一篇:在c#上@的3种作用
下一篇:JDBC连接MySQL和SQL Server的工具类及SQL Server连接报错的解决办法
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站