?符号 和 ?? 符号的作用。String的一些创建方式。结构体与类的区别。函数重载注意点及运算符的重载

?  符号:用于为 int,double,bool等无法赋值为null的数据类型进行null赋值
            如:  
            int i;  //默认为0
            int? i; //默认为Null
?? 符号:用于判断一个变量为Null时,给其赋一个值
            如:
            int? a = null;
            int n = a ?? 4; //如果a为null,则 n=4 ,否则 n=a;
            //Stingde 创建
            1.
            char[] a = {'a','b','c' };
            String s = new String(a);
            2.
            String[] a = {"aaa,"bbb",""bbb"};
            String s = String.Join("",a);
            3.
            其他创建方法
            //结构体与类的区别
            结构体:①不能定义析构函数,不能继承,是值类型,类是引用类型
                    ②构造函数默认,不能自定义构造函数
                    ③不能在申明时赋初值
            类在堆中,结构体在栈中。堆空间大,访问速度慢。栈空间小,访问速度快。
            轻量级用结构体。
            //函数重载注意点:
            ① 形参的类型或个数不同可以重载
            ② 如果只有返回参数的类型不同则不能进行重载
            //运算符可重载,用关键字 operator
            1.有一些要成对重载 如:==  !=
            2.不是所有运算符都可以重载
            3.比较运算符的重载需要返回bool,与其它的不一样
            4.无法重载 = 

例子如下:
public class Student {
        public String name;

        public Student(string v) {
            name = v;
        }
        //重载 + 符号
        //注意点:运算符重载函数必须写在对应的类的里面,不可写在对应的类之外
        public static Student operator +(Student s1, Student s2) {
            return new Student(s1.name + s2.name);
        }

}

    class Program {
        
        static void Main(string[] args) {
            Student s1 = new Student("名1");
            Student s2 = new Student("名2");
            //使用重载的 + 符号
            Student s3 = s1 + s2;
            Console.WriteLine(s3.name);
            

            Console.Read();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_38261174/article/details/84934535