C# REF关键字
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# REF关键字,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2488字,纯文字阅读大概需要4分钟。
内容图文
![C# REF关键字](/upload/InfoBanner/zyjiaocheng/629/581d32ee4b104149b2f3590418d7cb23.jpg)
C#中 ref 关键字的认识和理解
?之前接手老项目的时候有遇到一些的方法参数中使用了ref关键字加在传参的参数前面的情况。对于新手,这里介绍和讲解一下ref的用法和实际效果。
- CLR中默认所有方法的参数传递方式都是传值,也就是说不管你传递的对象是值类型还是引用类型,在作为参数传入到方法中时,传递的是原对象的副本。无论在方法中对该对象做何更改,都不影响外部的对象。
- 而使用了ref参数之后,传递的是对象的引用
- 对于值类型,传递的是值的引用,可以理解为值的地址
- 对于引用类型,传递的就是变量的引用,同样可以理解成变量的栈地址
值类型对象使用ref参数示例
?C# 控制台程序 值类型对象使用ref参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class Program { static void Main(string[] args) { int testInt = 10; Console.WriteLine(testInt); DoRef(ref testInt); Console.WriteLine(testInt); DoNotRef(testInt); Console.WriteLine(testInt); Console.ReadLine(); } public static void DoRef(ref int txt) { txt = 10000000; } public static void DoNotRef(int txt) { txt = 55555555; } } |
string类型对象使用ref参数示例
?C#?控制台程序?String类型对象使用ref关键字传参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Program { static void Main(string[] args) { string testValue = "origin"; Console.WriteLine(testValue); UseRef(ref testValue); Console.WriteLine(testValue); NotUseRef(testValue); Console.WriteLine(testValue); Console.ReadLine(); } public static void UseRef(ref string txt) { txt = "ref txt"; } public static void NotUseRef(string txt) { txt = "not ref txt"; } } |
类对象使用ref传参示例
?C# Code?控制台程序?类对象使用ref关键字传参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class Program { static void Main(string[] args) { TestModel t0 = new TestModel() { Text = "test" }; Console.WriteLine(t0.Text); UseRef(ref t0); Console.WriteLine(t0.Text); NotUseRef(t0); Console.WriteLine(t0.Text); Console.ReadLine(); } public static void UseRef(ref TestModel tModel) { tModel.Text = "use ref"; } public static void NotUseRef(TestModel tModel) { tModel.Text = "not use ref"; } } public class TestModel { public string Text { get; set; } } |
内容总结
以上是互联网集市为您收集整理的C# REF关键字全部内容,希望文章能够帮你解决C# REF关键字所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。