[C#]扩展方法

参考链接:

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method

0.定义扩展方法

a.静态类

b.静态方法

c.静态方法的第一个参数格式为:this + 要扩展的类名 + 该类的实例名

1.调用扩展方法

 1 using System;
 2 using UnityEngine;
 3 
 4 public static class StringExtension
 5 {
 6     public static string TestRepeat(this String str, int repeatCount)
 7     {
 8         string tempStr = str;
 9         for (int i = 0; i < repeatCount; i++)
10         {
11             tempStr = tempStr + str;
12         }
13         return tempStr;
14     }
15 }
16 
17 public class TestExtensionMethod : MonoBehaviour {
18 
19     void Start ()
20     {
21         string s = "hi";
22         string s2 = s.TestRepeat(2);
23         print(s2);//输出:hihihi
24     }
25 }

猜你喜欢

转载自www.cnblogs.com/lyh916/p/9220042.html