C#.NET中基本数据类型的奇妙发现

最近每天会坚持刷刷Leetcode, 在没有代码提示的情况下编码,刚开始真的比较难。没有了IDE提示,常用的C#语法/数据结构都用不顺溜,哎,这才忽然意识到, 对.NET基础类库的掌握真的不够熟练。有时候,为了完成一道"简单"的题目,还要去查基本数据类型(System, System.Collections.Generic)的使用。不过刷题顺便温习基础知识的时候发现,刚工作那会儿对一些概念并没有真的学透/掌握,或者说理解的不够深。这篇博客,主要记录一些C#.NET中基本数据类型的奇妙发现。顺便说一句,对基本数据类型/结构理解得更深,真的有利于又快又好地编码,感觉最近代码能力又长进了, 哈哈 😃 ~~

基本认知

  1. 内置类型中的值类型都是结构类型(Ref-1, Ref-2), 值类型包括两类: 结构类型和枚举类型。

  2. 虽然数字(整数实数), 字符以及时间是值类型(结构类型), 但是操作数字的数学算法,由字符组成的字符串及和时间相关的时区却是类,是引用类型(Ref)。

技术细节

  1. Char(官方注解) 和String(官方注解) , 包含ListArray

    // 1.使用索引器访问字符串时,索引位置访问的是单个Char对象
    string str = "Hello World!";
    for (int i = 0; i < str.Length; i++) {
      Console.WriteLine(str[i]);
    }
    
    // 2.由于String实现了IEnumerable<char>接口,所以使用以下语法初始化HashSet
    var hashSet = new HashSet<char>(str);
    
    // 3.几种常见的转换循环
    // 3-1.string <--> list<char>
    List<char> list = "abcd".ToList();   //string to list
    string str1 = string.Join("", list); //list to string
    
    // 3-2.string <--> char array
    var array1 = "abcd".ToCharArray(); //string to array
    //var array1 = "abcd".ToArray();   //string to array
    string str2 = new string(array1);  //array to string
    
    // 3-3.list<char> <--> char array
    var array2 = list.ToArray(); //list to array
    var list2 = array2.ToList(); //array to list
    
    // 3-4.string --> HashSet/Dictionary/Lookup
    var hashset = "12345".ToCharArray().ToHashSet();                    //string to HashSet
    var dict = "12345".ToCharArray().ToDictionary(x => x, x =>  x * x); //string to Dictionary
    var lookup = "123333".ToCharArray().ToLookup(x => x, x => x);       //string to Lookup
    
    // 4.几种创建重复字符串的方法 
    string myStr = "abc";
    int count = 5; //考虑count为0的情况
    
    // 4-1.LINQ
    var repeatStr1 = count > 0 ? Enumerable.Repeat(myStr, count).Aggregate((sum, next) => sum + next) : "";
    var repeatStr2 = new String(Enumerable.Range(0, count).SelectMany(x => myStr).ToArray());
    
    // 4-2.Concat & Join
    var repeatStr3 = String.Concat(Enumerable.Repeat(myStr, count));
    var repeatStr4 = string.Join("", Enumerable.Repeat(myStr, count));
    
    // 4-3.Replace
    var repeatStr5 = new String('X', count).Replace("X", myStr);
    var repeatStr6 = string.Empty.PadLeft(count, 'X').Replace("X", myStr);
    
    // 4-4.StringBuilder
    var repeatStr7 = new StringBuilder(myStr.Length * count).Insert(0, myStr, count).ToString();
    var repeatStr8 = new StringBuilder(myStr.Length * count).AppendJoin(myStr, new string[count + 1]).ToString();
    
  2. DictionaryLookup(官方注解, Ref-3)和HashSet的使用

    // Select complex List<Model> to Dictionary
    class User {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
    }
    
    List<User> Users = new List<User> {
        new User { Id = 1, Name = "Aaron", Gender ="Male" },
        new User { Id = 2, Name = "David", Gender ="Male" },
        new User { Id = 3, Name = "Lucy", Gender ="Female" },
        new User { Id = 4, Name = "Kate", Gender ="Female" }
    };
    
    var dict1 = Users.ToDictionary(o => o.Id, o => o.Name);
    var dict2 = Users.Select(t => new KeyValuePair<int, string>(t.Id, t.Name)).ToDictionary(x => x.Key, x => x.Value);
    
    // Use Lookup to map keys to collections of values,and handle null value
    var list = new List<string>() { "bye", "bye", "and", "see", "you", "tomorrow", null };
    var lookup  = list.ToLookup(x => x, x => x?.ToUpper());
    
    // Can't use ContainsKey(null) for Dictionary
    var dict3 = new Dictionary<string, string> {{"a", "1" }, {"b", "2" }, {"c", "3" }, {"d", "4" }};
    dict3.ContainsKey(null);  Exception --> System.ArgumentNullException: Value cannot be null.
    
    // Initial HashSet with List/Array
    var array = new int[] { 1, 1, 2, 2, 3, 3 };
    var hashSet1 = new HashSet<int>(array);
    
    var list = new string[] { "Bye", "Bye" };
    var hashSet2 = new HashSet<string>(list);
    
  3. DateTime相关的转换

    // 获取当前月的第一天
    var currentMonth = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
    
    // 获取明年第一天
    var nextYear = new DateTime(DateTime.Now.AddYears(1).Year, 1, 1);
    
  4. 枚举的常见使用

    // 枚举是特殊的值类型,是一组命名常量,和其他的自定义类型一样,既可以申明为非嵌套类型也可以申明为嵌套类型
    public enum Season { Spring = 1, Summer, Autumn, Winter }
    
    // 执行类型转换(还可以用Enum.Parse和Enum.TryParse)
    var a = Season.Autumn;
    Console.WriteLine($"{a} is {(int)a}rd season of the year"); // output: Autumn is 3rd season of a year
    
    var b = (Season)1;
    Console.WriteLine(b); // output: Summer
    
    var c = (Season)4;
    Console.WriteLine(c);  // output: 4
    
    // 使用 Enum.IsDefined 方法来确定枚举类型是否包含具有特定关联值的枚举成员
    var d = 3;
    Console.WriteLine($"Value {d} is in enum {nameof(Season)} : {Enum.IsDefined(typeof(Season), d)}"); 
    // output: Value 3 is in enum Season : True
    
    var e = "Summer"; // 注意字符串大小写敏感
    Console.WriteLine($"Value {e} is in enum {nameof(Season)} : {Enum.IsDefined(typeof(Season), e)}"); 
    // output: Value Summer is in enum Season : True
    
    // 循环访问枚举成员
    string[] names = Enum.GetNames(typeof(Season));
    foreach (var name in names) {
        Console.WriteLine($"{name} type is {name.GetType().Name}");
    }
    // output of the foreach loop:
    // Spring type is String
    // Summer type is String
    // Autumn type is String
    // Winter type is String
    
    var values = Enum.GetValues(typeof(Season));
    foreach (var element in values) {
        Console.WriteLine($"{element} type is {element.GetType().Name}");
    }
    // output of the foreach loop:
    // Spring type is Season
    // Summer type is Season
    // Autumn type is Season
    // Winter type is Season
    
    // 非独占成员和标志属性(枚举成员的关联值应该是2的幂)
    [Flags]
    public enum Days
    {
        None      = 0,
        Monday    = 1,
        Tuesday   = 2,
        Wednesday = 4,
        Thursday  = 8,
        Friday    = 16,
        Saturday  = 32,
        Sunday    = 64,
        Weekend   = Saturday | Sunday
    }
    
    Days meetingDays = Days.Monday | Days.Wednesday | Days.Friday;
    Console.WriteLine(meetingDays); // output: Monday, Wednesday, Friday
    
    // 添加枚举方法(该用法不常见, 不再举例)
    https://docs.microsoft.com/zh-cn/dotnet/api/system.enum?view=net-6.0#adding-enumeration-methods
    
    
    // 枚举设计准则
    https://docs.microsoft.com/zh-cn/dotnet/standard/design-guidelines/enum
    

持续更新中,未完待续。。。

posted @ 2020-08-16 00:02  天琊蓝  阅读(284)  评论(0编辑  收藏  举报