SoFunction
Updated on 2025-03-01

C# this keyword usage code detailed explanation

Usage 1: Extend method for primitive type

Let me first talk about the type followed by this, which is to expand the type of method. Pay attention to static methods written in static classes, otherwise access them in some cases

/// <summary>
  /// Extended class Used to extend methods for original classes  /// </summary>
  public static class AM_Extends
  {
    /// <summary>
    /// Extended a child method for the string class to implement a certain function    /// </summary>
    /// <param name="str"></param>
    /// <param name="new_str"></param>
    public static void Child( this string str,string new_str)
    {
      object obj = str;
      str=new_str;
    }
  }

Define extension method
private void Form1_Load(object sender, EventArgs e)
    {
      string st1 = "123";
      string st2 = "";
      string st3 = "";
      st3 = (st1);//The value of st3 is "123"    }

Calling instance

Usage 2 This represents the instance object of the current class

Usage 3 Use this concatenated constructor

public class Test
  {
    public Test()
    {
      ("No parameter constructor");
    }
    // This() corresponds to the parameterless constructor Test() // Execute Test() first, then execute Test(string text)    public Test(string text) : this()
    {
      (text);
      ("Argument constructor");
    }
  }

Usage 4 Indexer (encapsulated by EPList based on the indexer, used to optimize program performance problems caused by frequent Linq queries under big data, query data from list collection through index)

using System;
using ;
using ;
using ;
using ;

namespace 
{
  /// <summary>
  /// EPList supports creating indexes for List  /// </summary>
  /// <typeparam name="T">Type</typeparam>  public class EPList&lt;T&gt;
  {
    #region Member variables
    /// &lt;summary&gt;
    /// Index    /// &lt;/summary&gt;
    private List&lt;string[]&gt; m_Index = new List&lt;string[]&gt;();

    /// &lt;summary&gt;
    /// Cache data    /// &lt;/summary&gt;
    private Dictionary&lt;string, List&lt;T&gt;&gt; m_CachedData = new Dictionary&lt;string, List&lt;T&gt;&gt;();

    /// &lt;summary&gt;
    /// List data source    /// &lt;/summary&gt;
    private List&lt;T&gt; m_ListData = new List&lt;T&gt;();

    /// &lt;summary&gt;
    /// Get data through index values    /// &lt;/summary&gt;
    /// <param name="indexFields">IndexFields</param>    /// <param name="fieldValues">field value</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public List&lt;T&gt; this[string[] indexFields]
    {
      get
      {
        string key = (",", indexFields);
        if (m_CachedData.ContainsKey(key)) return m_CachedData[key];
        return new List&lt;T&gt;();
      }
    }

    #endregion

    #region Public Method
    /// &lt;summary&gt;
    /// Create an index    /// &lt;/summary&gt;
    /// <param name="indexFields">IndexFields</param>    public void CreateIndex(string[] indexFields)
    {
      if (m_Index.Contains(indexFields)) return;
      m_Index.Add(indexFields);
    }

    /// &lt;summary&gt;
    /// Add to    /// &lt;/summary&gt;
    /// <param name="record">Record</param>    public void Add(T record)
    {
      m_ListData.Add(record);
      m_Index.ForEach(indexFields =&gt;
      {
        string key = getKey(record, indexFields);
        if (m_CachedData.ContainsKey(key))
        {
          m_CachedData[key].Add(record);
        }
        else
        {
          List&lt;T&gt; list = new List&lt;T&gt; { record };
          m_CachedData.Add(key, list);
        }
      });
    }

    #endregion

    #region Private Method
    /// &lt;summary&gt;
    /// Get the value    /// &lt;/summary&gt;
    /// <param name="record">Record</param>    /// <param name="fieldName">Field name</param>    /// &lt;returns&gt;&lt;/returns&gt;
    private object getValue(T record, string fieldName)
    {
      Type type = typeof(T);
      PropertyInfo propertyInfo = (fieldName);
      return (record, null);
    }

    /// &lt;summary&gt;
    /// Get Key    /// &lt;/summary&gt;
    /// <param name="record">Record</param>    /// <param name="indexFields">IndexFields</param>    private string getKey(T record, string[] indexFields)
    {
      List&lt;string&gt; values = new List&lt;string&gt;();
      foreach (var field in indexFields)
      {
        string value = (getValue(record, field));
        (field + ":" + value);
      }
      return (",", values);
    }

    /// &lt;summary&gt;
    /// Get Key    /// &lt;/summary&gt;
    /// <param name="indexFields">IndexFields</param>    /// <param name="fieldValues">field value</param>    /// &lt;returns&gt;&lt;/returns&gt;
    private string getKey(string[] indexFields, object[] fieldValues)
    {
      if ( != ) return ;
      for (int i = 0; i &lt; ; i++)
      {
        fieldValues[i] = indexFields[i] + ":" + fieldValues[i];
      }
      string key = (",", fieldValues);
      return key;
    }

    #endregion
  }
}

 createEPList

Create an index for EPList and add data

private EPList&lt;SysDepartInfo&gt; GetEPListData()
{
  EPList&lt;SysDepartInfo&gt; eplist = new EPList&lt;SysDepartInfo&gt;();
  (new string[] { "ParentId" });
  string sql = "select Id,ParentId,Code,Name from SysDepart";
  (sql, null, (reader) =&gt;
  {
    SysDepartInfo record = new SysDepartInfo();
     = (reader["Id"]);
     = (reader["ParentId"]);
     = (reader["Code"]);
     = (reader["Name"]);
    (record);
  });
  return eplist;
}

GiveEPListCreate an index,And add data
private EPList<SysDepartInfo> GetEPListData()
{
EPList<SysDepartInfo> eplist = new EPList<SysDepartInfo>();
(new string[] { "ParentId" });
string sql = "select Id,ParentId,Code,Name from SysDepart";
(sql, null, (reader) =>
{
SysDepartInfo record = new SysDepartInfo();
 = (reader["Id"]);
 = (reader["ParentId"]);
 = (reader["Code"]);
 = (reader["Name"]);
(record);
});
return eplist;
}

Create an index for EPList and add data

/// &lt;summary&gt;
/// Get child nodes/// &lt;/summary&gt;
/// &lt;param name="data"&gt;&lt;/param&gt;
/// &lt;param name="parentId"&gt;&lt;/param&gt;
private IEnumerable&lt;TreeInfo&gt; CreateChildren(EPList&lt;SysDepartInfo&gt; data, TreeInfo node)
{
  string id = node == null ? "0" : ;
  List&lt;TreeInfo&gt; childNodes = new List&lt;TreeInfo&gt;();
  // The index is created on the ParentId field, so here you can directly extract the next layer of child node data through the index value to avoid the efficiency problems caused by Linq query  var indexValues = new string[] { "ParentId:" + id };
  var childData = data[indexValues];
  (record =&gt;
  {
    var childNode = new TreeInfo
    {
      id = ,
      text =  + " " + 
    };
    (childNode);
     = CreateChildren(data, childNode);
  });
  return (record =&gt; );
}

Efficient query of data through index