您的位置:首页 > 其它

通过类似GetComponent从组件中直接获得接口的三种方式

2016-10-28 09:41 495 查看
孙广东  2016.10.15 http://blog.csdn.net/u010019717
功能类似于   GetComponents  等函数:

1、  不用接口, 使用抽象类    继承自  Monobehaiour
public abstract class LayerPanelBase :MonoBehaviour
{
public abstract void InitView(HeroModel heroModel, CharacterAttributeView characterAttributeView);
}


然后执行   .GetComponent<LayerPanelBase>().InitView(myHeroModel, this);

2、原理类似   网上百度可见的:
原帖:
 http://forum.unity3d.com/threads/60596-GetComponents-Possible-to-use-with-C-Interfaces
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public static class GameObjectEx
{
public static T GetInterface<T>(this GameObject inObj) where T : class
{
if (!typeof(T).IsInterface)
{
Debug.LogError(typeof(T).ToString() + ": is not an actual interface!");

return null;
}
var tmps = inObj.GetComponents<Component>().OfType<T>();
if (tmps.Count()==0) return null;
return tmps.First();
}

public static IEnumerable<T> GetInterfaces<T>(this GameObject inObj) where T : class
{
if (!typeof(T).IsInterface)
{
Debug.LogError(typeof(T).ToString() + ": is not an actual interface!");
return Enumerable.Empty<T>();
}

return inObj.GetComponents<Component>().OfType<T>();
}
}


定义的时候直接使用  Interface  这种方式最好了!

3、使用Linq  :
var controllers = GetComponents<MonoBehaviour>()
.Where(item => item is IInfiniteScrollSetup)
.Select(item => item as IInfiniteScrollSetup)
.ToList();

扩展方法:
public static List<T> GetInterfaces<T>(this GameObject obj) where T: class
{
return obj.GetComponents<MonoBehaviour>()
.Where(item => item is T)
.Select(item => item as T)
.ToList();
}


没办法提供    GetComponent   这种  找一个的方式。
所以相对来来讲还是 第二种  GetInterface  找接口的一个
GetInterfaces    找接口的多个!
http://blog.csdn.net/u010019717
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐