search
HomeBackend DevelopmentC#.Net Tutorial.NET Framework- Summary of codes used 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 delegateFunction:

//ForEach方法:public void ForEach(Action<T> action);//委托声明:public delegate void Action<in T>(T obj);

The delegate 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, return A value must be assigned to the function before.
2) When calling a function, parameters with out do not need to be assigned an initial value.
3) out formal parameter Passing value is 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未按照预想逻辑被赋值。

There is a type of TryParse function in C#.net, which is another important application of out. If you are interested, see: Through Parse and TryParse: Try-Parse and Tester-Doer patterns

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);
//调用reviseModel
reviseModel(model.a); //model.a仍然=10;by-value
reviseMode(ref model.a); //编译不过,提示ref后的参数不归类与变量
int a;
reviseMode(ref a); //如果不给变量a赋一个初始值,
//编译器也是提示:调用前未被赋值的错误
//因此赋值
int a= model.a; //变量a初始值为10;
reviseMode(ref a);//修改变量a=12;但是model.a的值仍然为10

How to modify the attribute a in the object model to change it to 12?

//直接将参数设为Model对象,则函数调用时,传值通过by referencepublic void reviseModel(Model md)
{
  md.a = 12;
}

reviseModel(model );//传值通过by reference

Therefore, a summary of the use of the ref keyword:
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.

1) The variable after ref, if it is a value type, then after adding ref, it becomes a value passed by reference;

2) The variable after ref, if it is Reference type (reference type), then there is no difference between adding ref or not;

3) The variable after ref must be assigned a value before use

4) The variable after ref cannot be a reference Type attributes

The above is a basic analysis, which is enough in use. If you want to analyze this issue more deeply, please continue.

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.

The code written using the Try... method is 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) {
  // ...}

but val == null, both It may be that there is no key-value pair with the key in the map, or it may be that the key-value pair already exists but its value is 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);
  // ...}

The internal operations of containsKey() and get() are almost exactly the same. They both need to do a hash search, but they just return different parts of the search results. In other words, if you write it according to this "correct writing method", accessing HashMap once will have double the cost. Cups!

C# has many such detailed designs that are more considerate than Java. See how C# uses the out keyword to improve this problem.

System.Collections.Generic.Dictionary

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

Using this method, the C# version corresponding to the above Java code can be written as:

// Dictionary<TKey, TValue> dict;
// TKey key;
TValue val;if (dict.TryGetValue(key, out val)) {
  // ...}

This combines ContainsKey and Item[ Key] semantics are combined to return all the information that can be found in a hash search at one go, avoiding the redundant operation of "two searches" from the source, which is beneficial to the performance of the program.

C#.net provides a keyword params. I didn’t know this keyword existed before. Once, after a colleague saw several versions of my overloaded functions, he calmly said to me, brother Yeah, you can use params. I checked it later and now I’m used to it. I just removed all the previous versions and refactored it using params.

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.

Query method based on 4 key fields:

        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);

        }

The getPlansWithCondition method called is

        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);
        }
        }

问题来了,当查询再新加1个字段时,你难道还再重载一个版本吗?

5.2 应用params

 private List<MPartPlan> getMPartPlansWithCondition(DateTime dateTime, DateTime dateEndTime, string planStat, string contactNo,string newField);

当C#提供了params后,当然不用,直接将getMPartPlansWithCondition改写为如下

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);

5.3 总结

queryFun(params object[] objs),带有这个参数的函数,只需要一个版本,这样解决了因为个数不一致而导致的多个重载版本,
在客户端调用时,将属性参数一一列数即可。

The above is the detailed content of .NET Framework- Summary of codes used in, out, ref, paras. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft