优雅的C#

  1. @符号:字符串中的转义符不转义,可支持字符串换行,例如:string test = "hello\\",正常输出hello\,改成string test = @"hello\\",输出hello\\
  2. ??:a??b??c,a为null,返回b,b也为null,返回c
  3. $:相当于string.Format,string test = $"{变量} test"
  4. 使用属性,好处是可以将成员变量的读写权限分开
    public GameObject ComGameObject
    {
    get => this.comObj;
    set => this.comObj = value;
    }
  5. 条件属性,运行时的行为,区别有条件编译,代码更优雅

            [Conditional("DEBUG")]
            static void Print1()
            {
                Console.WriteLine("You defined the Debug parameter");
            }

  6. 等同性判断
    public static bool ReferenceEquals(object left, object right); (判断引用,值类型回false)
    public static bool Equals(object left, object right); (都可以判断,引用同上,值判断用的是反射,效率低)
    public virtual bool Equals(object right); (重写时,需要重写GetHashCode,用作为MapKey时)
    public static bool operator ==(MyClass left, MyClass right);(值类型都要重写)
  7. 短小方法,在C#中代码先被变成IL,然后在运行前被JIT编译成Native Code。JIT是按照方法进行编译的,也就是说它会在真正需要某一个方法之前编译它。这样,尽可能小的方法会减少我们程序的载入时间
    在C#中写短小,清晰的方法。这样不会让我们的程序变慢,而会使我们的程序更容易理解,载入更快
  8. 值类型和引用类型的选择——如果只是数据的存储,并且所有 public 的接口(属性和方法)都是只是访问数据而不是修改数据才使用值类型,其他情况都选择引用类型
  9. new 在派生类里使用,可以显示地屏蔽基类中相同名字的内容

posted on 2020-02-26 21:15  胖福  阅读(322)  评论(0编辑  收藏  举报

导航