• Field initializers & Conditional operator


    Field initializers

    赋值可以直接给值,也可以是对象。

    建议不直接给filed initialzer赋值,当继承的时候会出现顺序的怪异问题:

    解决方法:在constructor里给filed赋值

    注意如果是继承类,自己ctor之前先要ctor基类。叫public Person()的时候会先跳到上面的基类public Base()先。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication2
    {
        static class Whoa
        {
            public static int GetInt(string from)
            {
                Console.WriteLine("Getting an int from {0}", from);
                return 4;
            }
        }
        class Base
        {
            private int _baseStuff;
            public Base()
            {
                _baseStuff = Whoa.GetInt("Base._baseStuff");
                Whoa.GetInt("From base ctor");
            }
        }
        class Person : Base
        {
            private int _health;
            private int _mana;
            private int _whoa;
            public Person()
            {
                _health = Whoa.GetInt("Person._health");
                _mana = Whoa.GetInt("Person._mana");
                _whoa = Whoa.GetInt("Person._whoa");
                Whoa.GetInt("From person ctor");
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                var p = new Person();
                Console.ReadKey();
            }
        }
    }
    View Code

    Conditional operator

     

    一级运算符: !

    二级运算符: >=

     三级运算符:  condition expression1 :expression2  任何type都可以放在expression里除了void,两个expression的type要可以互相转换

    var whoa = age >= 21 ? int.Parse("123") : 123; //返回值是int
    
    var db1 = age >=  21 ? Stuff() : Whoa(); //返回值是double
    
    static int Stuff()
    {
        return 4;
    }
    static int Whoa()
    {
        return 32.3232;
    }

    var toPrint = age>= 21 ? 34141.ToString() : "You are not buy this";

    Console.WriteLine("You {0} buy alcohol in the states!", age >= 21 : "can", "can't"); //最好的写法

    注意对操作数的限制:要可以互相转化。比如's'和23.2就被最终转换成了double类型,那么这个三级运算返回值就是一个double的。

    后面alchohol那段两个操作数都是string所以,三级运算整个返回的是一个string类型,可以在Console.WriteLine()里。

    再来一个复杂点的:

     

    Null coalescing operator

     

     return account ?? NotLoggedInAccount; 等同于

    return account != null ? account : NotLoggedInAccount;

    ask account是否不是null,如果不是返回左边的如果是返回右边的

     

  • 相关阅读:
    github中建立pages
    批处理指令_windows定时关机脚本
    批处理指令_同步数据脚本
    python_笔记
    python_操作outlook
    按键精灵_一些踩过的坑
    linux_一些踩过的坑
    python_快速排序
    python_jira库的一些常用操作
    jira_一些踩过的坑
  • 原文地址:https://www.cnblogs.com/shawnzxx/p/3137717.html
Copyright © 2020-2023  润新知