• 第二篇 .NET高级技术之密闭类和静态类及扩展方法


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

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

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

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

    4、静态类和密封类的不同在于密封类是可以New,静态类不能NEW,同时也没有什么可比性

    using System;

    using System.Collections;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    namespace TestConsole

    {

        class Program

        {

            static void Main(string[] args)

            {

                string str = "Hello World!";

                str.ShowMsg(str);

                Console.ReadKey();

            }

    }

        #region 扩展方法

        static class MyString

        {

            public static void ShowMsg(this string a, string msg)

            {

                Console.WriteLine(msg);

            }

        }

        #endregion 扩展方法

    }

    更多技术请关注

  • 相关阅读:
    微信小程序HTTPS
    微信商城-1简介
    va_list
    Event log c++ sample.
    EVENT LOGGING
    Analyze Program Runtime Stack
    unknow table alarmtemp error when drop database (mysql)
    This application has request the Runtime to terminate it in an unusual way.
    How to check if Visual Studio 2005 SP1 is installed
    SetUnhandledExceptionFilter
  • 原文地址:https://www.cnblogs.com/dullbaby/p/10910629.html
Copyright © 2020-2023  润新知