厦门市建设执业资格注册管理中心网站,网站系统建设系广告经营者,怎么开微信小程序店铺,哈尔滨网站建设那家好关键点#xff1a;
定义扩展方法的类和方法必须是静态的#xff1a; 扩展方法必须在一个静态类中定义。扩展方法本身也必须是静态的。第一个参数使用 this 关键字#xff1a; 扩展方法的第一个参数指定要扩展的类型#xff0c;并且在这个参数前加上 this 关键字。这个参数…关键点
定义扩展方法的类和方法必须是静态的 扩展方法必须在一个静态类中定义。扩展方法本身也必须是静态的。第一个参数使用 this 关键字 扩展方法的第一个参数指定要扩展的类型并且在这个参数前加上 this 关键字。这个参数表示方法将应用于哪个类型的实例。调用方式 虽然扩展方法是静态方法但你可以像调用实例方法一样调用它。仅适用于引用类型、值类型和接口 你不能为 null、void 或泛型类型参数定义扩展方法。优先级 如果扩展方法与类型本身的方法发生冲突方法签名相同那么类型本身的方法将优先被调用。命名空间 扩展方法必须在使用前通过 using 语句引入其命名空间。
代码例子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public static class tools
{public static void AtLookTarget(this Transform obj,Transform target){Vector3 var target.position - obj.position;obj.rotation Quaternion.LookRotation(var);}
} 使用扩展方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class siyausnhuchangyonff : MonoBehaviour
{public Transform lookA;public Transform lookB;void Update(){lookA.AtLookTarget(lookB);}
}