Explain about vsual c# box and nu-box
2008-04-17 15:27
141 查看
简单的说,装箱就是将值类型(value type)转换为引用类型(reference type)的过程;反之,就是拆箱。
频繁装箱和拆箱操作会降低程序效率,因此在编写的时候要尽量避免(比如2.0中的泛型概念)。
.NET中所有类型都是对象,所有类型的根是System.Object。
类型分为值类型(value)和引用类型(regerence type)。C#中定义的值类型包括:原类型(Sbyte、Byte、Short、Ushort、Int、Uint、Long、Ulong、Char、Float、Double、Bool、Decimal)、枚举(enum)、结构(struct)。引用类型包括:类、数组、接口、委托、字符串等。
实例一:读下列程序,你能说出其中进行了几次装箱和拆箱的操作吗?
using System;
class sample1
{
public static void Main()
{
int i=10;
object obj=i;
Console.WriteLine(i+","+(int)obj);
}
}
其中发生了三次装箱操作和一次拆箱操作。第一次object obj=i;将i装箱;而Console.WriteLine方法用的参数是String对象,因此,i+","+(int)obj中,i需要进行一次装箱(转换成String对象),(int)obj将obj对象拆箱成值类型,而根据WriteLine方法,比较将(int)obj值装箱成引用类型。
示例参考:http://www.itwis.com/html/net/c/20080402/1183.html
/article/5975575.html (性能分析)
/article/7070189.html
频繁装箱和拆箱操作会降低程序效率,因此在编写的时候要尽量避免(比如2.0中的泛型概念)。
.NET中所有类型都是对象,所有类型的根是System.Object。
类型分为值类型(value)和引用类型(regerence type)。C#中定义的值类型包括:原类型(Sbyte、Byte、Short、Ushort、Int、Uint、Long、Ulong、Char、Float、Double、Bool、Decimal)、枚举(enum)、结构(struct)。引用类型包括:类、数组、接口、委托、字符串等。
实例一:读下列程序,你能说出其中进行了几次装箱和拆箱的操作吗?
using System;
class sample1
{
public static void Main()
{
int i=10;
object obj=i;
Console.WriteLine(i+","+(int)obj);
}
}
其中发生了三次装箱操作和一次拆箱操作。第一次object obj=i;将i装箱;而Console.WriteLine方法用的参数是String对象,因此,i+","+(int)obj中,i需要进行一次装箱(转换成String对象),(int)obj将obj对象拆箱成值类型,而根据WriteLine方法,比较将(int)obj值装箱成引用类型。
示例参考:http://www.itwis.com/html/net/c/20080402/1183.html
/article/5975575.html (性能分析)
/article/7070189.html
相关文章推荐
- 2. C# - Learning About Built-In Types and Variables
- Task cancellation in C# and things you should know about it
- A question about C++ static method and C# static method
- c# dynamic,maybe I should say it is just some shortcut for "Object", box and unbox, without the cast
- Part 61 to 63 Talking about partial class and partial method in C#
- A little thought about .NET Framework, CTS, CLI, CLS, CLR and C#
- About CSS Box-Model and Flow
- An article about Equals and GetHashCode functions in C#
- Working with PDF files in C# using PdfBox and IKVM
- Part 72 to 81 Talking about Dictionary and List collection in C#
- An article about Equals and GetHashCode functions in C#
- Information About The Space of MFC and C#,ASP.NET
- details about rtp and rtcp
- C# constructor chain and extension method
- Effective C# Item 20: Distinguish Between Implementing Interfaces and Overriding Virtual Functions
- iOS.ReactNative-3-about-viewmanager-uimanager-and-bridgemodule
- About Servers and Clients
- Pro .NET 2.0 Windows Forms and Custom Controls in C#
- AMO olap Test C# generate tsql and mdx
- About Words and Deeds