Detailed introduction to the use of C# in, out, ref, paras
C#.net provides 4 keywords, in, out, ref, paras, which are often used in development, so how to use them? What is the difference?
1 in
in is only used in delegates and interfaces;
Example:
//测试模型 class Model { public int a { get; set; } public Model(int a) { this.a = a; } }//创建3个实例List<Model> modelList= new List<Model>() { new Model(1), new Model(4), new Model(6) };//调用foreach接口,试着操作3个实例,赋值为nullmodelList.ForEach(e=>e=null); //查看结果://modelList的取值不变。
Analysis of the reason, the parameter of ForEach is the delegate function:
//ForEach方法:public void ForEach(Action<T> action);//委托声明:public delegate void Action<in T>(T obj);
Delegation It is generic, and a keyword in is added before the type T. Because of the keyword in, T obj cannot be modified.
Try the test:
//修改元素e的属性amodelList.ForEach(e=>{e.a*=2;});
As a result, each element is multiplied by 2, becoming 2,8,12. It can be seen that the properties of the object can be modified.
2 out
Out keyword usage notes:
1) For formal parameters with out, when the function is defined, one must be assigned to the function before return value.
2) When calling a function, parameters with out do not need to be assigned an initial value.
3) The value of the out formal parameter is passed by reference (by reference)
out usage scenario:
When a function returns multiple values, out is usually used to return one of them
public bool Operation(out Model updateMod) { updateMode = new Model(5); try{ // my operation ... // return true; } catch{ //写入日志 return false; } }//使用Model um; //未初始化bool rtnMsg = Operation(out um); //如果初始化,传值通过reference//分析://返回um,如果rntMsg为ture,则um按照预想逻辑被赋值, //如果rntMsg为false 则um未按照预想逻辑被赋值。
3 ref
ref keyword is used to change parameter passing, Change by value to by reference. The original value is passed by reference. The effect is the same with or without ref. For example:public void reviseModel(int a) { a = 12; } Model model = new Model(10); //调用reviseModelreviseModel(model.a); //model.a仍然=10;by-valuereviseMode(ref model.a); //编译不过,提示ref后的参数不归类与变量int a; reviseMode(ref a); //如果不给变量a赋一个初始值, //编译器也是提示:调用前未被赋值的错误 //因此赋值int a= model.a; //变量a初始值为10;reviseMode(ref a); //修改变量a=12;但是model.a的值仍然为10
//直接将参数设为Model对象,则函数调用时,传值通过by referencepublic void reviseModel(Model md) { md.a = 12; } reviseModel(model );//传值通过by reference
ref is used to process value variables, such as basic types, structures, etc. They do not need to be new, and value transfer is based on value copy.
4 In-depth discussion of out ref
Mainly analyze the use of out ref and what impact they will have if they are not used. 1) There is a class of methods in C# called Try..., such as Int.TryParse. It returns a bool value and tries to parse a string. If it is successfully parsed into an integer, it returns true and the resulting integer is The int is passed as the second out.See analysis article
Exception design guidelines
Through Parse and TryParse: Try-Parse and Tester-Doer modes
It can be seen from the article that compared to the sub-method Parse without out parameters, if parsed If the string fails, a parameter error exception will be thrown.
more concise than the code written using try...catch, so this has become a common scenario for using out parameters.
2) Comparison between Java and C#In Java, HashMap// HashMap<K, V> map; // K key; V val = map.get(key);if (val != null) { // ...}
To distinguish between the two, HashMap provides the containsKey() method. So the correct way to write it is this:
// HashMap<K, V> map; // K key;if (map.containsKey(key)) { V val = map.get(key); // ...}
TryGetValue: Dictionary(TKey, TValue).TryGetValue Method (TKey, TValue) (System.Collections.Generic)public bool TryGetValue( TKey key, out TValue value )ParameterskeyType: TKey The key of the value to get. valueType: TValue
// Dictionary<TKey, TValue> dict; // TKey key; TValue val;if (dict.TryGetValue(key, out val)) { // ...}
5 Paras
So, I will talk about the use of params and the process I went through. 5.1 Requirements of the problem On the client side, customers often change the fields they query. A few days ago, they went to the server to query several models based on four key fields. Today, they want to add one more Query field.
public void GetPlansByInputControl(string planState, string contactno,DatePair dp) { string planStat = ""; switch (planState) { case "...": planStat = "..."; break; case "...": planStat = "..."; break; } plans = getPlansWithCondition(Convert.ToDateTime(dp.startValue), Convert.ToDateTime(dp.endValue), planStat, contactno); }
private List<MPartPlan> getMPartPlansWithCondition(DateTime dateTime, DateTime dateEndTime, string planStat, string contactNo) { var conditions = new CslSqlBaseSingleTable(); conditions.AddCondition("RequireStartDate", dateTime, DataCompareType.GreaterOrEqual); conditions.AddCondition("RequireStartDate", dateEndTime, DataCompareType.LessOrEqual); conditions.AddCondition("OrderCode", contactNo, DataCompareType.Equal); if (!string.IsNullOrEmpty(planStat)) { conditions.AddCondition("PlanState", planStat, DataCompareType.Equal); } return _cslMPartPlan.QueryListInSingleTable(typeof(MPartPlan), conditions); } }
private List<MPartPlan> getMPartPlansWithCondition(DateTime dateTime, DateTime dateEndTime, string planStat, string contactNo,string newField);
private List<MPartPlan> getMPartPlansWithCondition(params object[] queryConditions); { queryConditions[0] queryConditions[1] queryConditions[2] queryConditions[3] queryConditions[4] //放到字典中dict sqlQuery(dict); }
_bsl.GetPlansByInputControl(field1, field2,field3,field4,field5);
queryFun(params object[] objs), a function with this parameter only requires one version, which solves the problem of multiple overloaded versions due to inconsistent numbers.
When called by the client, The attribute parameters can be listed one by one.
The 4 keywords provided by C#.net, in, out, ref, and paras are often used in development, so how to use them? What is the difference?
The above is C# A detailed introduction to the use of in, out, ref, paras. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.
