使用扩展函数,可以为无法修改源代码的对象添加新的方法,或者强制让对象支持某些方法,这些方法看起来就是对象本来就有的功能。
static class中定义,所以必须使用static修饰;this修饰;从简单程度上来说,使用扩展方法明显比使用传统方式要简单很多,不需要实例化,修改方法也不需要重新修改和编译。
那为什么扩展方法没有得到很大的推广呢?(不足之处)
override的能力,不会重载原有的方法;namespace可见的,并通过使用using namespace来导入其他命名空间中的扩展方法。namespace下的静态类的静态方法,最后为较远的namespace下的静态类的静态方法。该功能就是使用扩展函数来实现的,平时在项目中自己使用的,这里做个例子,来表现一下扩展函数的功能。
using System;
using UnityEngine;
namespace my_code
{
/// 定向子节点组件
public static class ChildNodeComponent
{
/// 获取子节点组件
/// 父节点对象
/// 组件类型
/// 子节点名称路径
/// 子节点组件
public static Component GetComponentInChildren(this Transform parnet, Type type, string namepath = null)
{
Transform temp = parnet;
if (!string.IsNullOrEmpty(namepath))
{
string[] node = namepath.Split('/');
for (int i = 0; i < node.Length; i++)
{
temp = temp.Find(node[i]);
}
}
return temp.GetComponent(type);
}
/// 获取子节点组件
/// 组件类型
/// 父节点对象
/// 子节点名称路径
/// 子节点组件
public static T GetComponentInChildren<T>(this Transform parnet, string namepath = null) where T : Component
{
return GetComponentInChildren(parnet, typeof(T), namepath) as T;
}
/// 获取子节点组件
/// 父节点对象
/// 组件类型
/// 子节点名称路径
/// 子节点组件
public static Component GetComponentInChildren(this GameObject parnet, Type type, string namepath = null)
{
return GetComponentInChildren(parnet.transform, type, namepath);
}
/// 获取子节点组件
/// 组件类型
/// 父节点对象
/// 子节点名称路径
/// 子节点组件
public static T GetComponentInChildren<T>(this GameObject parnet, string namepath = null) where T : Component
{
return GetComponentInChildren(parnet, typeof(T), namepath) as T;
}
}
}
下面就是具体的使用方法:
m_slider = statenode.GetComponentInChildren<Slider>("ProgressBarBG");
m_tooltip = statenode.GetComponentInChildren<Transform>("Tooltip").gameObject;
m_back = m_stateNode.GetComponentInChildren<Button>("TitleBG/Back");
m_title = m_stateNode.GetComponentInChildren<Text>("TitleBG/Title");
与Unity自带的GetComponentInChildren不一样的就是后面的参数是一个字符串(以各层子节点名称以及分隔符'/'组成)。