C# 使用笔记

本文详细介绍了C#中条件运算符(三目运算符)?和空合并操作符(??)的用法。通过实例展示了如何在代码中使用这些操作符进行条件判断和处理可能的null值。同时,提到了string.Intern方法的作用,它将字符串放入常驻池,确保相同字符串共享同一内存地址。此外,还讨论了DebuggerNonUserCode特性,用于禁止对特定函数进行单步调试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

各种"?"用法

  1. a ?b:c : 判断a为真返回b,否则c
  2. t? :声明可空类型t
  3. a??b: a 为真返a, 否则b
  4. a?.c : a 为真,返回其属性c, 否则是空的可空类型
  5. a?[i] : a 为真,返回索引i的值,否则是空的可空类型
int i = 23 > 12 ? 23 : 12;
Debug.Log(string.Format("23 > 12 ? 23 : 12: {0}", i));
TestInfo info = new TestInfo();
int? ii = info?.c;
Debug.Log(string.Format("info?.c: {0}", ii));
info = null;
ii = info?.c;
Debug.Log(string.Format("info?.c: {0}", ii.ToString()));
info = info ?? new TestInfo();
Debug.Log(string.Format("info?.c: {0}", info.c));

int[] tt = { 1, 1, 34, 2, 34, 3, 343 };
List<int> testLst = new List<int>(tt); 
testLst.AddRange(tt);
int? iii = testLst?[2];
Debug.Log(string.Format("testLst?[10]; {0}", iii.ToString()));

string.Intern

  1. 使用对应的字符串变成常驻池中的字符串,这样之后相同的字符串,他们都是使用同一个内存,返回是同一个内存地址.
        string a = "Hello world";
        string b = string.Intern(a);
        Debug.Log(string.Format("a is b ? {0}", ReferenceEquals(a, b))); // true
        string c = string.Copy(a);
        Debug.Log(string.Format("c is a ? {0}", ReferenceEquals(c, a))); // false

System.Diagnostics.DebuggerNonUserCode

  1. 对该函数不能单步调试(F10),即使可以打断点,但一定执行下一步,必然直接跳出函数到执行结束的步骤
  2. DebuggerNonUserCodeAttribute 是针对属性的
    [global::System.Diagnostics.DebuggerNonUserCode]
    void TestStringIntern() {
        string a = "Hello world";
        string b = string.Intern(a);
        Debug.Log(string.Format("a is b ? {0}", ReferenceEquals(a, b))); // true
        string c = string.Copy(a);
        Debug.Log(string.Format("c is a ? {0}", ReferenceEquals(c, a))); // false
        int k = this.test_value;
        int abc = 232;
        k += abc;
    }

    int m_test_value = 0;

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    public int test_value {
        get { 
            return m_test_value; 
        }
        set {
            m_test_value = value;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值