- 扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。
- 特点:
- 静态类
- 扩展方法为静态方法
- 扩展方法第一个参数前加this;
- ToInt():为float扩展方法;
- ChangeString():为string扩展方法。
using UnityEngine;
public class test : MonoBehaviour
{
private void Start()
{
//在其他类里可直接调用
float f = 10.1f;
f.ToInt();
string str = "helloworld";
str.ChangeString();
//在本类里直接调用
A.Run();
}
}
public static class A
{
public static void Run()
{
float f = 10.1f;
f.ToInt();
string str = "helloworld";
str.ChangeString();
}
public static void ToInt(this float a)//将float转int
{
Debug.Log((int)a);
}
public static void ChangeString(this string str)//字符串大写
{
Debug.Log(str.ToUpper());
}
}