首页 > 编程语言 >C# this关键字的四种用法

C# this关键字的四种用法

时间:2024-06-13 11:32:28浏览次数:24  
标签:return string record C# List 用法 关键字 new public

用法一  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(); } } } }
复制代码 复制代码

用法三  为原始类型扩展方法

特点:1、静态类 2、静态方法 3、第一个参数前加this

例如:public static List<T> ToList<T>(this string Json),就是为this对应的string类型扩展类ToList()方法,调用方式 strJson.ToList();

详细扩展

复制代码
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创建索引,并添加数据

复制代码 复制代码
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;
}
复制代码 复制代码

通过索引高效查询数据

复制代码
/// <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); }

标签:return,string,record,C#,List,用法,关键字,new,public
From: https://www.cnblogs.com/raincedar/p/18245575

相关文章

  • ALoRA: Allocating Low-Rank Adaptation for Fine-tuning Large Language Models
    本文是LLM系列文章,针对《ALoRA:AllocatingLow-RankAdaptationforFine-tuningLargeLanguageModels》的翻译。ALoRA:为微调大型语言模型分配低秩自适应摘要1引言2相关工作3方法4实验5结论摘要参数有效微调(PEFT)在大语言模型时代因其有效性和效率而......
  • Aligning with Human Judgement: The Role of Pairwise Preference in Large Language
    本文是LLM系列文章,针对《AligningwithHumanJudgement:TheRoleofPairwisePreferenceinLargeLanguageModelEvaluators》的翻译。与人类判断相一致:配对偏好在大型语言模型评估者中的作用摘要1引言2LLM计算器校准的局限性3不确定性引导的成对偏好搜索4......
  • CSP_J_真题之 2023 第一轮笔试(一)
    公众号:编程驿站......
  • Linux上12个最佳开源ChatGPT替代方案
    ​ChatGPT是OpenAI开发的流行聊天机器人和虚拟助手,自2022年11月30日起上市。此图表模型可让您对对话进行微调并引导其达到理想的持续时间、结构、语气、细节程度和语言。幸运的是,随着人工智能的不断进步,开源ChartGPT替代品已经成为强大的工具,可以提供相同的对话技巧以及定......
  • Docker的Namespace隔离技术
    什么是NamespaceNamespace是Linux内核的一项功能,该功能对内核资源进行分区,以使一组进程看到一组资源,而另一组进程看到另一组资源。Namespace的工作方式通过为一组资源和进程设置相同的Namespace而起作用,但是这些Namespace引用了不同的资源。资源可能存在于多个Namespace......
  • JsSIP+FreeSwitch+Vue实现WebRtc音视频通话
    效果让同事帮我测的,在两个电脑分别打开该页面,一个注册1007分机号,另一个注册1005,然后拨打视频电话依赖版本jssip:3.6.1freeswitch:1.10.5-release~64bitvue:2.6.12488错误解决在freeswitch配置文件sip_profiles/internal.xml中添加:<paramname="apply-can......
  • 探索鸿蒙系统中的OffscreenCanvas并发线程绘制问题
    引言作为一名热衷于鸿蒙系统开发的工程师,我近期遇到了一个关于OffscreenCanvas组件在并发线程中绘制时崩溃的问题。这个问题不仅挑战了我的技术理解,也促使我深入探索鸿蒙系统的内部机制。在这篇文章中,我将分享我的发现和解决问题的过程。问题描述在开发过程中,我尝试使用O......
  • 解决@LocalStorageProp值同步问题的详细指南
    在华为鸿蒙操作系统(HarmonyOS)的开发中,@LocalStorageProp是一个关键的装饰器,用于在页面级别的UI状态存储中实现数据的单向同步。然而,开发者在使用@LocalStorageProp时可能会遇到值未按预期同步的问题。本文将详细介绍如何正确使用@LocalStorageProp,并通过父组件的状态更新来......
  • vue3 修改element-plus主题颜色(css版)
    vue3修改主题颜色_若依vue3改默认主题色-CSDN博客上面的是js修改-----------------------------------------------------------------------------------------------------------------------1.新建一个APPStyle.css文件代码/*8这里是要替换的样式,可以参开下面注释......
  • 实操教程|PyTorch实现断点继续训练
    作者丨HUST小菜鸡(已授权)编辑丨极市平台最近在尝试用CIFAR10训练分类问题的时候,由于数据集体量比较大,训练的过程中时间比较长,有时候想给停下来,但是停下来了之后就得重新训练,之前师兄让我们学习断点继续训练及继续训练的时候注意epoch的改变等,今天上午给大致整理了一下,不全面......