C#| this作用:为参数类型扩展方法

  • 扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。
  • 特点:
  1. 静态类 
  2. 扩展方法为静态方法
  3. 扩展方法第一个参数前加this;
  • 代码示例:两个扩展方法:
  1. ToInt():为float扩展方法;
  2. 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());
    }
}
发布了162 篇原创文章 · 获赞 20 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_39766005/article/details/90636640
今日推荐