C#关键字explicit、implicit、operator 、unsafe 、fixed
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#关键字explicit、implicit、operator 、unsafe 、fixed,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2100字,纯文字阅读大概需要4分钟。
内容图文
今天遇到一些一般不常用,但说不定什么情况下就能用到的C#关键字。
转换关键字
explicit 定义强制转换
// Must be defined inside a class called Fahrenheit: public static explicit operator Celsius(Fahrenheit fahr) { return new Celsius((5.0f / 9.0f) * (fahr.degrees - 32)); }
implicit 定义隐性转换
// User-defined conversion from Digit to double public static implicit operator double (Digit d) { return d.val; }
operator 定义重载操作符号
详情MSDN: http://msdn.microsoft.com/zh-cn/library/39bb81c3.aspx
C#使用指针
unsafe 关键字表示不安全上下文,该上下文是任何涉及指针的操作所必需的。
fixed 语句禁止垃圾回收器重定位可移动的变量。 fixed 语句只在不安全的上下文中是允许的。 Fixed 还可用于创建固定大小缓冲区。
// The unsafe keyword allows pointers to be used within // the following method: static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count) { if (src == null || srcIndex < 0 || dst == null || dstIndex < 0 || count < 0) { thrownew ArgumentException(); } int srcLen = src.Length; int dstLen = dst.Length; if (srcLen - srcIndex < count || dstLen - dstIndex < count) { thrownew ArgumentException(); } // The following fixed statement pins the location of // the src and dst objects in memory so that they will // not be moved by garbage collection. fixed (byte* pSrc = src, pDst = dst) { byte* ps = pSrc; byte* pd = pDst; // Loop over the count in blocks of 4 bytes, copying an // integer (4 bytes) at a time:for (int n = 0; n < count / 4; n++) { *((int*)pd) = *((int*)ps); pd += 4; ps += 4; } // Complete the copy by moving any bytes that weren‘t // moved in blocks of 4:for (int n = 0; n < count % 4; n++) { *pd = *ps; pd++; ps++; } } } staticvoid Main(string[] args) { byte[] a = newbyte[100]; byte[] b = newbyte[100]; for (int i = 0; i < 100; ++i) a[i] = (byte)i; Copy(a, 0, b, 0, 100); Console.WriteLine("The first 10 elements are:"); for (int i = 0; i < 10; ++i) Console.Write(b[i] + ""); Console.WriteLine("\n"); }
详情MSDN:
http://msdn.microsoft.com/zh-cn/library/chfa2zb8.aspx
http://msdn.microsoft.com/zh-cn/library/f58wzh21.aspx
原文:http://www.cnblogs.com/hkflyor/p/3714334.html
内容总结
以上是互联网集市为您收集整理的C#关键字explicit、implicit、operator 、unsafe 、fixed全部内容,希望文章能够帮你解决C#关键字explicit、implicit、operator 、unsafe 、fixed所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。