您的位置:首页 > 编程语言 > C#

C#基础篇 结构:在结构中定义构造函数

2014-01-10 11:28 162 查看

结构具有以下特点:

结构是类型,而类是引用类型
与类不同,结构的实例化可以不使用new运算符
结构可以声明构造函数,但是它必须带有参数
一个结构不能从另一个结构或者类继承,而且不能作为其他结构或者类的基类
结构可以实现接口
结构可以用null值对结构成员进行赋值

在实例化时,可以通过new关键字进行实例化,也可以不通过new关键字进行实例化

struct ABC

{

        public string Name;

}

ABC wm = new ABC();   //通过new关键字实例化

Console.WriteLine(wm.Name);   //输出为空

/****************************/

ABC wm2;

Console.WriteLine(wm2.Name);   //错误!!!

/**************************/

在结构中只能创建带有参数的构造函数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace wm110_1
{
class Program
{
struct CoConfiguration
{
public CoConfiguration(string Name, Object Leaguer, string Address, int Phone)  //定义构造函数
{
CoName = Name;
CoLeaguer = Leaguer;
CoAddress = Address;
CoPhone = Phone;
}
public string CoName;
public Object CoLeaguer;
public string CoAddress;
public int CoPhone;
}
struct Leaguer
{
public Leaguer(string M, string BM, string E)   //定义构造函数
{
Mgr = M;
BranchMgr = BM;
Employee = E;
}
public string Mgr;
public string BranchMgr;
public string Employee;
}
static void Main(string[] args)
{
Leaguer leaguer = new Leaguer("赛某","刘某","孙某"); //实例化同时,通过构造函数赋值
CoConfiguration coconf = new CoConfiguration("微软",leaguer,"西安",123456);   //用new关键字进行实例化
string branchMgr = ((Leaguer)coconf.CoLeaguer).BranchMgr;  //获取子结构中的成员值
Console.WriteLine(coconf.CoName +"公司,部门经理:"+branchMgr);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息