一些知识的提升:密闭类和静态类、深拷贝和浅拷贝

1.密闭类和静态类

1、密闭类是修饰为sealed的类, sealed不能有子类。一般只有系统中的一些基本类声明为sealed。面试题:是否可以编写一个类继承自String类?

答:不能,因为string被声明为了sealed了

2、静态类:声明为static的类,不能实例化,只能定义static成员。通常用他定义扩展方法

3、C#3.0特性:扩展方法。声明静态类,增加一个静态方法,第一个参数是被扩展类型的标记为this,然后在其他类中可以直接调用,本质上还是对静态方法调用提供的一个“语法糖”,也可以用普通静态方法的方式调用,所以不能访问private和protected成员。例子:给String扩展一个IsEmail方法。自己写的机会比较少。

usingSystem;

usingSystem.Collections;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

namespaceTestConsole

{

    class Program

    {

        static void Main(string[] args) {

            string str = "HelloWorld!";

  str.ShowMsg(str);

            Console.ReadKey();

        }

}

    #region 扩展方法

    static class MyString

    {

        public static void ShowMsg(this string a, stringmsg)

        {

            Console.WriteLine(msg);

        }

    }

    #endregion 扩展方法

}



2.深拷贝、浅拷贝

如果拷贝的时候共享被引用的对象就是浅拷贝,如果被引用的对象也拷贝一份出来就是深拷贝。(深拷贝就是说重新new一个对象,然后把之前的那个对象的属性值在重新赋值给这个用户)

usingSystem;

usingSystem.Collections;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;


namespaceTestConsole

{

    class Program

    {

        static void Main(string[] args)

        {

            MyCopy copy1 = new TestConsole.MyCopy();

            copy1.Name ="蛋蛋";

            copy1.Age =18;

            MyCopy copy2 = copy1;//浅拷贝

            MyCopy copy3 = new MyCopy();

            copy3.Name =copy1.Name;

            copy3.Age =copy1.Age;//深拷贝

            Console.ReadKey();

        }

}

    #region 深拷贝、浅拷贝

    class MyCopy

    {

        public string Name { get; set; }

        public int Age { get; set; }

    }

    #endregion 深拷贝、浅拷贝

}},  "JWoIVy�Z�T%�

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容