日期:2014-05-18  浏览次数:21369 次

C#中的结构类型为什么不能直接对属性赋值?
程序一(直接对结构中的字段赋值,可以):
C# code

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

namespace 结构
{
    struct IDCard
    {
        public  int id;
        public  string name;
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }    
    }
    class Program
    {
        static void Main(string[] args)
        {
            IDCard idc;
            idc.id = 12345;         //直接对字段赋值
            idc.name = "张四 ";     //直接对字段赋值
            Console.WriteLine("身份证号码:{0},姓名:{1}",idc .Id ,idc .Name );
            Console.ReadKey();        
        }
    }
}


运行结果:
身份证号码:12345,姓名:张四

程序二(直接对结构中的属性赋值,出错):
C# code

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

namespace 结构
{
    struct IDCard
    {
        public  int id;
        public  string name;
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        public string Name
        {
            get { return name; }
            set { name = value; }
        }    
    }
    class Program
    {
        static void Main(string[] args)
        {
            IDCard idc;
            [u]idc.Id = 12345;[/u]         //直接对属性赋值
            idc.Name = "张四 ";            //直接对属性赋值
            Console.WriteLine("身份证号码:{0},姓名:{1}",idc .Id ,idc .Name );
            Console.ReadKey();        
        }
    }
}


出错提示:
内容:Use of unassigned local variable 'idc' 行数:(上面带下划线的一行)

求解释。

------解决方案--------------------
IDCard idc = new IDCard();
------解决方案--------------------
结构类型一般的习惯是不用属性访问器的。

结构类型很多时候要跟其他的编程语言接轨,所以直接使用公共字段好些。
------解决方案--------------------
我觉得结构如果声明时不用 new 实例化,在给公共字段赋值时就自动实例化了。
属性等同于方法,直接调用方法并不会实例化它,而如果先给字段赋值,再调用方法就可以的了。
------解决方案--------------------
接4楼,而且是所有字段都要赋值,如果有私有字段就只能 new 了
------解决方案--------------------
探讨
引用:
IDCard idc = new IDCard();

有两个疑问:
1、结构体默认有一个同名构造函数?
2、结构体不是在声明时就已经向各成员分配存储空间了,为什么还需要专门的构造函数?

------解决方案--------------------
探讨

我觉得结构如果声明时不用 new 实例化,在给公共字段赋值时就自动实例化了。
属性等同于方法,直接调用方法并不会实例化它,而如果先给字段赋值,再调用方法就可以的了。

------解决方案--------------------
探讨

补充:程序二中出错的一行是 idc.Id = 12345; //直接对属性赋值
(不知道为什么帖子中的下划线没有显示出来?)