zoukankan      html  css  js  c++  java
  • 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,如果不是返回左边的如果是返回右边的

     

  • 相关阅读:
    Android笔记(五十七)Android总结:基础篇
    Android笔记(五十六) Android四大组件之一——ContentProvider,实现自己的ContentProvider
    Android笔记(五十五) Android四大组件之一——ContentProvider,使用系统提供的ContentProvider
    Python类定义
    Python 作用域和命名空间
    Python 默认参数值
    Python 关键字参数和可变参数
    Python常用函数--return 语句
    Python常用函数--文档字符串DocStrings
    如何编写 Python 程序
  • 原文地址:https://www.cnblogs.com/shawnzxx/p/3137717.html
Copyright © 2011-2022 走看看