. NET Framework-in, out, ref, paras code summary used

Source: Internet
Author: User
C#.net provides 4 keywords that are often used in in,out,ref,paras development, so how do they work? What's the difference?





1 in



In is used only in delegates and interfaces;
Example:



// test model
        class Model
         {
         public int a {get; set;}
         public Model (int a)
             {
             this.a = a;
             }
         } // Create 3 instances List <Model> modelList = new List <Model> ()
{new Model (1), new Model (4), new Model (6)}; // Call the foreach interface and try to operate 3 instances, assigning nullmodelList.ForEach (e => e = null);

// View the result: // The value of modelList does not change.


For analysis reasons, the arguments to foreach are delegate functions:


foreach method: public void ForEach (action<t> Action);//Delegate declaration: public delegate void Action<in t> (T obj);

 


The delegate is generic, and the type T is preceded by a keyword in, so T obj cannot be modified because it has the keyword in.



Try the test:



Modify the attribute of element e Amodellist.foreach (e=>{e.a*=2;});


As a result, each element is multiplied by 2 to become 2,8,12. You can modify the properties of an object.



2 out



Out Keyword Usage Note:
1) A formal parameter with an out, which must be assigned a value before the return of the function definition.
2) when calling a function, a parameter with an out does not have to assign an initial value.
3) out parameter value is passed by reference (by reference)



Out usage Scenario:
When a function returns multiple values, it is usually used out to return one of the



public bool Operation (out Model updateMod)
{
     updateMode = new Model (5);
     try {
     // my operation
      ...
      //
      return true;
     } catch {// write to log
       return false;
     }
}
//use
Model um; // Not initialized
bool rtnMsg = Operation (out um); // If initialized, pass the value through the reference
//analysis:
// Return um. If rntMsg is true, um is assigned according to the expected logic.
// If rntMsg is false, then um is not assigned according to the expected logic.


There is a class of TryParse function in C#.net, which is another important application of out. If interested, see: Through the parse and Tryparse:try-parse and Tester-doer modes



3 ref



The REF keyword is used to change the pass of the parameter, modifying by value to the by reference value, which is passed by reference, plus ref or no ref, the effect is the same.



For example:



public void reviseModel (int a)
{
   a = 12;
}

Model model = new Model (10);
// call reviseModel
reviseModel (model.a); //model.a is still = 10; by-value
reviseMode (ref model.a); // Compile, but the parameter after ref is not classified and variable
int a;
reviseMode (ref a); // If you do not assign an initial value to the variable a,
// The compiler also prompts: an error that was not assigned before the call
// as a result
int a = model.a; // The initial value of variable a is 10;
reviseMode (ref a); // Modify the variable a = 12; but the value of model.a is still 10


How do I modify the property A in the object model to make it 12?




// Set the parameter directly to the Model object, and when the function is called, the value is passed by referencepublic void reviseModel (Model md)
{
   md.a = 12;
}

reviseModel (model); // Pass the value by by reference


Therefore, the REF keyword uses a summary:
Ref, used to process value variables, such as basic types, structures, etc., they do not need to be new, the value is based on the value of the copy.



1) The variable after ref, if it is a value type (value), then add ref to the value by reference;



2) ref variable, if it is a reference type (reference type), then add ref with no difference;



3) The variable after ref, must be assigned before use



4) A variable after ref cannot be a property of a reference type



The above is the basic analysis, in use is enough, if you want to further analyze the problem, please continue.



4 in-depth discussion of out ref



The main analysis of out ref exactly what is the use, without them will have any effect.



1) There is a class of methods in C #, called Try ..., such as Int.tryparse, which returns a bool value, attempts to parse a string, and if successfully resolves to an integer, returns True, and the resulting integer is outgoing as the second out int.
See Analysis articles
Exception Design Guidelines
Through the parse and Tryparse:try-parse and Tester-doer modes
As you can see from the article, if parsing a string fails, it throws an exception with the wrong argument, compared to the secondary method with no out parameter.



With a Try ... The code written by the method is more concise than that written by Try...catch, so it becomes a common scenario used by out parameters.



2) Java and C # comparison



In Java, HashMap



Hashmap<k, v> map;//K key; V val = map.get (key); if (val! = null) {  //...}


But val = = null, which is either a key-value pair that has not already been keyed to the key in the map, or it may already have the key-value pair but its value is null.
To differentiate between the two, HashMap provides the ContainsKey () method. So the correct wording is this:



Hashmap<k, v> map;//K key;if (Map.containskey (key)) {  V val = map.get (key);  // ...}


ContainsKey () is almost identical to the internal operation of Get (), which is to do a hash lookup, just to return the different parts of the search results. That is to say, according to this "correct writing" to write, visit once HashMap has doubled the cost. Cups!



C # has many of these details designed to be more intimate than Java. See how C # uses out keywords to improve the 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 Java code corresponding to the C # version can be written as:




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


This combines the semantics of ContainsKey and Item[key], and returns the information that can be found by a hash lookup, avoiding the redundant operation of "two lookups" from the source, which is beneficial to the performance of the program.



C#.net provides a keyword params, previously did not know that there is this keyword, once, colleagues see my several version of the overloaded function, calmly and I said a sentence, elder brother, you can use the params, later checked, and now often used, this does not just again to write a few versions have taken off, and re-refactored it with the params.



5 Paras



Well, I'll just say the use of the params, the process I've been through.



5.1 The need for a problem
On the client side, the customer often changes the query field, the first few days or according to 4 key fields to the server query several models, today, and want to add 1 query fields.



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


The question is, do you want to reload another version when the query adds 1 more fields?



5.2 Application Params




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


When C # provides the params, of course not, rewrite getmpartplanswithcondition directly as follows



private List <MPartPlan> getMPartPlansWithCondition (params object [] queryConditions);
{
    queryConditions [0]
    queryConditions [1]
    queryConditions [2]
    queryConditions [3]
    queryConditions [4]
    // put in the dictionary dict

    sqlQuery (dict);
} 


After the arbitrary addition of query fields, as long as the modification of this function on the line, do not add or delete overloaded version!!!



Client call, just add a field to the line



_BSL. Getplansbyinputcontrol (field1, FIELD2,FIELD3,FIELD4,FIELD5);


5.3 Summary



Queryfun (params object[] objs), a function with this parameter, requires only one version, which resolves multiple overloaded versions resulting from inconsistent numbers.
When the client calls, the attribute parameter one by one is the number of columns.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.