【01】密闭类、静态类(*)、扩展方法

1、密闭类是修饰为sealed的类, sealed不能有子类。一般只有系统中的一些基本类声明为sealed。

面试题:是否可以编写一个类继承自String类?

答:String类是sealed类故不可以继承。
当对一个类应用 sealed 修饰符时,此修饰符会阻止其他类从该类继承。

2、静态类:声明为static的类,不能实例化,只能定义static成员。

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

1)定义和调用扩展方法

  • 定义包含扩展方法的静态类。
  • 此类必须对客户端代码可见。 有关可访问性规则的详细信息,请参阅访问修饰符。
  • 将扩展方法实现为静态方法,并且使其可见性至少与所在类的可见性相同。
  • 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符。
  • 在调用代码中,添加 using 指令,用于指定包含扩展方法类的命名空间。
  • 和调用类型的实例方法那样调用这些方法。
  • 请注意,第一个参数并不是由调用代码指定,因为它表示要在其上应用运算符的类型,并且编译器已经知道对象的类型。 你只需通过 n 提供形参 2 的实参。

2)示例

以下示例实现 CustomExtensions.StringExtension 类中名为 WordCount 的扩展方法。 此方法对 String 类进行操作,该类指定为第一个方法参数。 将 CustomExtensions 命名空间导入应用程序命名空间,并在 Main 方法内部调用此方法。

using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    //Extension methods must be defined in a static class
    public static class StringExtension
    {
        // This is the extension method.
        // The first parameter takes the "this" modifier
        // and specifies the type for which the method is defined.
        public static int WordCount(this String str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    //Import the extension method namespace.
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            //  Call the method as if it were an 
            //  instance method on the type. Note that the first
            //  parameter is not specified by the calling code.
            int i = s.WordCount();
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}
原文地址:https://www.cnblogs.com/lolitagis02/p/8187959.html