C# this關鍵字的四種用法(轉)

用法一  this表明當前類的實例對象

namespace Demo
{
    public class Test
    {
        private string scope = "全局變量";
        public string getResult()
        {
            string scope = "局部變量";
       // this表明Test的實例對象
       // 因此this.scope對應的是全局變量
        // scope對應的是getResult方法內的局部變量
            return this.scope + "-" + scope;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Test test = new Test();
                Console.WriteLine(test.getResult());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.ReadLine();
            }

        }
    }
}

用法二  用this串聯構造函數

namespace Demo
{
    public class Test
    {
        public Test()
        {
            Console.WriteLine("無參構造函數");
        }
        // this()對應無參構造方法Test()
     // 先執行Test(),後執行Test(string text)
        public Test(string text) : this()
        {
            Console.WriteLine(text);
            Console.WriteLine("有參構造函數");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Test test = new Test("張三");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }
}

用法三  爲原始類型擴展方法

namespace Demo
{
    public static class Extends
    {
     // string類型擴展ToJson方法
        public static object ToJson(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject(Json);
        }
        // object類型擴展ToJson方法
        public static string ToJson(this object obj)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static string ToJson(this object obj, string datetimeformats)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static T ToObject<T>(this string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
        }
        public static List<T> ToList<T>(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
        }
        public static DataTable ToTable(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
        }
        public static JObject ToJObject(this string Json)
        {
            return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                List<User> users = new List<User>{
                    new User{ID="1",Code="zs",Name="張三"},
                    new User{ID="2",Code="ls",Name="李四"}
                };

                // list轉化json字符串
                string json = users.ToJson();
          // string轉化List
                users = json.ToList<User>();

                // string轉化DataTable
                DataTable dt = json.ToTable();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }

    public class User
    {
        public string ID { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
    }
}

用法四  索引器(基於索引器封裝EPList,用於優化大數據下頻發的Linq查詢引起的程序性能問題,經過索引從list集合中查詢數據)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace MyDemo.Web
{
    /// <summary>
    /// EPList 支持爲List建立索引
    /// </summary>
    /// <typeparam name="T">類型</typeparam>
    public class EPList<T>
    {
        #region 成員變量

        /// <summary>
        /// 索引
        /// </summary>
        private List<string[]> m_Index = new List<string[]>();

        /// <summary>
        /// 緩存數據
        /// </summary>
        private Dictionary<string, List<T>> m_CachedData = new Dictionary<string, List<T>>();

        /// <summary>
        /// List數據源
        /// </summary>
        private List<T> m_ListData = new List<T>();

        /// <summary>
        /// 經過索引值取數據
        /// </summary>
        /// <param name="indexFields">索引字段</param>
        /// <param name="fieldValues">字段值</param>
        /// <returns></returns>
        public List<T> this[string[] indexFields]
        {
            get
            {
                string key = string.Join(",", indexFields);
                if (m_CachedData.ContainsKey(key)) return m_CachedData[key];
                return new List<T>();
            }
        }

        #endregion

        #region 公共方法

        /// <summary>
        /// 建立索引
        /// </summary>
        /// <param name="indexFields">索引字段</param>
        public void CreateIndex(string[] indexFields)
        {
            if (m_Index.Contains(indexFields)) return;
            m_Index.Add(indexFields);
        }

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

        #endregion

        #region 私有方法

        /// <summary>
        /// 獲取值
        /// </summary>
        /// <param name="record">記錄</param>
        /// <param name="fieldName">字段名</param>
        /// <returns></returns>
        private object getValue(T record, string fieldName)
        {
            Type type = typeof(T);
            PropertyInfo propertyInfo = type.GetProperty(fieldName);
            return propertyInfo.GetValue(record, null);
        }

        /// <summary>
        /// 獲取Key
        /// </summary>
        /// <param name="record">記錄</param>
        /// <param name="indexFields">索引字段</param>
        private string getKey(T record, string[] indexFields)
        {
            List<string> values = new List<string>();
            foreach (var field in indexFields)
            {
                string value = Convert.ToString(getValue(record, field));
                values.Add(field + ":" + value);
            }
            return string.Join(",", values);
        }

        /// <summary>
        /// 獲取Key
        /// </summary>
        /// <param name="indexFields">索引字段</param>
        /// <param name="fieldValues">字段值</param>
        /// <returns></returns>
        private string getKey(string[] indexFields, object[] fieldValues)
        {
            if (indexFields.Length != fieldValues.Length) return string.Empty;
            for (int i = 0; i < indexFields.Length; i++)
            {
                fieldValues[i] = indexFields[i] + ":" + fieldValues[i];
            }
            string key = string.Join(",", fieldValues);
            return key;
        }

        #endregion
    }
}

給EPList建立索引,並添加數據node

private EPList<SysDepartInfo> GetEPListData()
{
    EPList<SysDepartInfo> eplist = new EPList<SysDepartInfo>();
    eplist.CreateIndex(new string[] { "ParentId" });
    string sql = "select Id,ParentId,Code,Name from SysDepart";
    SqlHelper.ExecuteReader(sql, null, (reader) =>
    {
        SysDepartInfo record = new SysDepartInfo();
        record.Id = Convert.ToString(reader["Id"]);
        record.ParentId = Convert.ToString(reader["ParentId"]);
        record.Code = Convert.ToString(reader["Code"]);
        record.Name = Convert.ToString(reader["Name"]);
        eplist.Add(record);
    });
    return eplist;
}

經過索引高效查詢數據sql

/// <summary>
/// 獲取子節點
/// </summary>
/// <param name="data"></param>
/// <param name="parentId"></param>
private IEnumerable<TreeInfo> CreateChildren(EPList<SysDepartInfo> data, TreeInfo node)
{
    string id = node == null ? "0" : node.id;
    List<TreeInfo> childNodes = new List<TreeInfo>();
    // ParentId字段上建立了索引,因此這裏就能夠經過索引值直接取出下一層子節點數據,避免Linq查詢引起的效率問題
    var indexValues = new string[] { "ParentId:" + id };
    var childData = data[indexValues];
    childData.ForEach(record =>
    {
        var childNode = new TreeInfo
        {
            id = record.Id,
            text = record.Code + " " + record.Name
        };
        childNodes.Add(childNode);
        childNode.children = CreateChildren(data, childNode);
    });
    return childNodes.OrderBy(record => record.text);
}
相關文章
相關標籤/搜索