C# this

1.C#原始类型扩展方法—this参数修饰符

https://www.cnblogs.com/jhxk/articles/1796382.html

扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。对于用 C# 和 Visual Basic 编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。

      扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。仅当您使用 using 指令将命名空间显式导入到源代码中之后,扩展方法才位于范围中。

  下面的示例演示为 System.String 类定义的一个扩展方法。请注意,它是在非嵌套、非泛型静态类内部定义的:
     namespace ExtensionMethods
     {
         public static class MyExtensions
         {
             public static int WordCount(this String str)
             {
                 return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
             }
         }   
     }


  可使用以下 using 指令将 WordCount 扩展方法放入范围中:
  using ExtensionMethods;
  而且,可以在应用程序中使用以下语法对该扩展方法进行调用:
  string s = "Hello Extension Methods";
  int i = s.WordCount();

  在代码中,可以使用实例方法语法调用该扩展方法。但是,编译器生成的中间语言 (IL) 会将代码转换为对静态方法的调用。因此,并未真正违反封装原则。实际上,扩展方法无法访问它们所扩展的类型中的私有变量。

2.C#构造函数中:this()的作用

https://www.cnblogs.com/luguangguang/p/8418337.html

this()用来继承无参时的构造函数,例如下面代码


    static void Main(string[] args)
        {
            AA aA = new AA("c","d");
            Console.WriteLine(aA.aa);
            Console.WriteLine(aA.bb);
            Console.WriteLine(aA.cc);
            Console.WriteLine(aA.dd);
            Console.WriteLine(aA.ee);

            Console.ReadKey();
        }
    }
    class AA
    {
      public  string aa="aa 未初始化";
      public  string bb= "bb 未初始化";
      public  string cc= "cc未初始化";
      public  string dd= "dd 未初始化";
      public  string ee= "ee 未初始化";
        public AA(string c,string d):this()
        {
            this.cc = c;
            this.dd = d;
        }
        public AA()
        {
            this.aa = "a";
            this.bb = "b";
        }
    }

猜你喜欢

转载自blog.csdn.net/yaoyutian/article/details/88918313
C#