c#中结构体structure初始化

    技术2026-04-23  3

    1. c# structure基本事实

    2. 初始化问题

    3. 总结

     


     

    1. c# structure基本事实

     

    c# structure为值类型,和class是相类似,但是c#中的class是引用类型。

     


     

    2. 初始化问题

     

    下面是两段代码,看上去是相似的,但是其中一段代码是不能够编译的:

    public struct StructMember { public int a; public int b; }

    public struct StructProperties { private int a; private int b; public int A { get { return a; } set { a = value; } } public int B { get { return b; } set { b = value; } } }

    public class MainClass { public static void Main() { StructMembers MembersStruct; StructProperties PropertiesStruct; MembersStruct.X = 100; MembersStruct.Y = 200; PropertiesStruct.X = 100; PropertiesStruct.Y = 200; } }

     

    上面的代码编译出如下错误:

     

    error CS0165: Use of unassigned local variable 'PropertiesStruct

    单纯通过c#代码是无法看出错误,通过查看上面代码生成的反汇编,可以看出PropertiesStruct的get方法,需要使用new关键字新生成一个instance。但是MembersStruct生成的汇编代码的话,没有生成method,显然通过这种赋值的方式是能够实现的。

     

     


    3. 总结

     

    Using the new operator calls the default constructor of the specific type and assigns the default value

    to the variable.


    最新回复(0)