C# class and struct

本文介绍了C#中类和结构的基础概念,包括类作为引用类型如何通过变量持有对象的引用,以及结构作为值类型如何复制整个对象。同时,还探讨了实例创建、对象赋值以及客户代码如何使用这些变量来调用对象的方法和访问公共属性。

"A class or struct definition is like a blueprint that specifies what the type can do. An object is basically a block of memory that has been allocated and configured according to the blueprint. A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object. In an object-oriented language such as C#, a typical program consists of multiple objects interacting dynamically."

---from Microsoft Developer Network


Class

"Because classes are reference types, a variable of a class object holds a reference to the address of the object on the managed heap. If a second object of the same type is assigned to the first object, then both variables refer to the object at that address. This point is discussed in more detail later in this topic."


<span>	</span>Country country1 = new Country();
<span>	</span>//new object being created using class
<span>	</span>
<span>	</span>Country country2 =country1;
<span>	</span>// assigning country2 to the same reference as country1
<span>	</span>// so that country 1 and 2 contain the references to the same address, any change made on country2 results in change on country1
</pre><pre name="code" class="csharp">

struct

"Because structs are value types, a variable of a struct object holds a copy of the entire object"


<span>	</span>Country C1 = new C1();
<span>	</span>
<span>	</span>Country C2 = C1;
<span>	</span>// the whole object of C1 is copied to C2, meaning that there are now two objects(a new object is created)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值