C#之this的使用

时间:2023-03-10 04:10:56
C#之this的使用

1.限定类似名称隐藏的成员

 public Employee(string name, string alias)
{
// Use this to qualify the fields, name and alias:
this.name = name;
this.alias = alias;
}

2.将对象作为参数传递给方法

 CalcTax(this);  

3.声明索引器

静态成员函数,因为它们存在于类级别且不属于对象,不具有 this 指针。 在静态方法中引用 this 是错误的。

 public int this[int param]
{
get { return array[param]; }
set { array[param] = value; }
}

4.实现扩展的方法

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

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

扩展方法必须在非泛型静态类中定义。

      如果扩展方法与该类型中定义的方法具有相同的签名,则扩展方法永远不会被调用。

 namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}

可使用 WordCount 指令将 using 扩展方法置于范围中;

   using ExtensionMethods;  

而且,可以使用以下语法从应用程序中调用该扩展方法:

   string s = "Hello Extension Methods";
int i = s.WordCount();

5.使用扩展方法扩展类或接口

可以使用扩展方法来扩展类或接口,但不能重写扩展方法。 与接口或类方法具有相同名称和签名的扩展方法永远不会被调用。 编译时,扩展方法的优先级总是比类型本身中定义的实例方法低。换句话说,如果某个类型具有一个名为 Process(int i) 的方法,而你有一个具有相同签名的扩展方法,则编译器总是绑定到该实例方法。 当编译器遇到方法调用时,它首先在该类型的实例方法中寻找匹配的方法。 如果未找到任何匹配方法,编译器将搜索为该类型定义的任何扩展方法,并且绑定到它找到的第一个扩展方法。

定义接口:

     public interface IMyInterface
{
void MethodB();
}

定义扩展方法:

     public static class ExtensionInterface
{
public static void MethodA(this IMyInterface myInterface,int i)
{
Console.WriteLine
("Extension.MethodA(this IMyInterface myInterface, int i)");
}
public static void MethodA(this IMyInterface myInterface, string s)
{
Console.WriteLine
("Extension.MethodA(this IMyInterface myInterface, string s)");
}
// This method is never called in ExtensionMethodsDemo1, because each
// of the three classes A, B, and C implements a method named MethodB
// that has a matching signature.
public static void MethodB(this IMyInterface myInterface)
{
Console.WriteLine
("Extension.MethodB(this IMyInterface myInterface)");
}
}

实现接口:

     class A : IMyInterface
{
public void MethodB() { Console.WriteLine("A.MethodB()"); }
} class B : IMyInterface
{
public void MethodB() { Console.WriteLine("B.MethodB()"); }
public void MethodA(int i) { Console.WriteLine("B.MethodA(int i)"); }
} class C : IMyInterface
{
public void MethodB() { Console.WriteLine("C.MethodB()"); }
public void MethodA(object obj)
{
Console.WriteLine("C.MethodA(object obj)");
}
}

测试接口扩展:

 static void Main(string[] args)
{
// Declare an instance of class A, class B, and class C.
A a = new A();
B b = new B();
C c = new C(); // For a, b, and c, call the following methods:
// -- MethodA with an int argument
// -- MethodA with a string argument
// -- MethodB with no argument. // A contains no MethodA, so each call to MethodA resolves to
// the extension method that has a matching signature.
a.MethodA(); // Extension.MethodA(IMyInterface, int)
a.MethodA("hello"); // Extension.MethodA(IMyInterface, string) // A has a method that matches the signature of the following call
// to MethodB.
a.MethodB(); // A.MethodB() // B has methods that match the signatures of the following
// method calls.
b.MethodA(); // B.MethodA(int)
b.MethodB(); // B.MethodB() // B has no matching method for the following call, but
// class Extension does.
b.MethodA("hello"); // Extension.MethodA(IMyInterface, string) // C contains an instance method that matches each of the following
// method calls.
c.MethodA(); // C.MethodA(object)
c.MethodA("hello"); // C.MethodA(object)
c.MethodB(); // C.MethodB() Console.ReadLine();
}

6.转自

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/this

随机推荐

  1. from live writer

    <body> <div class="pagination"> <a href="#" class="first&quo ...

  2. CSS核心的几个概念

    盒模型.position.float.他们是css的基础,之间看似独立却又相辅相成. 元素类型 块级元素.内联元素 他们之间有以下区别: 1.块级元素独占一行,除非显示的修改display属性.而内联 ...

  3. C# Emit动态代理生成一个实体对象

    /// <summary> /// 使用Emit动态代理收集实体信息 /// </summary> /// <typeparam name="T"&g ...

  4. CF451D Count Good Substrings (DP)

    Codeforces Round #258 (Div. 2) Count Good Substrings D. Count Good Substrings time limit per test 2 ...

  5. [译]git config

    git config git config命令用来设置git的一些配置(包括全局配置和针对单个仓储的配置).git config命令能定义一个仓储的用户信息和用户偏好. 用法 git config u ...

  6. asp.net—缓存

    1.页面缓存 要实现页面输出缓存,只要将一条 OutputCache 指令添加到页面即可. <%@ OutputCache CacheProfile=" " NoStore= ...

  7. 一张图告诉你,只会jQuery还不够!

    会了jquery语法,会了jquery函数,你就真的会了jquery吗,来看这张图!是超实用的jquery代码段一书的导览!熊孩子们,赶紧学习去吧! 对于码农来说,代码就是生产力,你每天能码多少行并不 ...

  8. 2012Chengdu B (快速组合数)

    B - Candy Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit St ...

  9. Mahout 介绍

    1.Hbase+k-means  (G级别) 2.k-means+mr (T级别) 1. 2.canopy 2.贝叶斯算法 决策,分类,文档分类 3.推荐系统 4.图书推荐系统 1.需求 付完款的用户 ...

  10. Spark之Streaming

    1. socket消息发送 import java.net.ServerSocket import java.io.PrintWriter import scala.collection.mutabl ...