Unity3D 判断脚本是否继承了某个接口或者类

简要笔记

判断脚本是否继承了某个对象

public TestForCheck obj  

void Start()
{
        #region 方法1,判断是否继承了某个接口或者类
        Type t = typeof(IActionForLicenseCheck);
        Type tt = typeof(TestForCheck);
        Debug.Log("方法1:"+t.IsAssignableFrom(tt));
        #endregion

        #region 方法2,判断是否继承了某个接口
        Debug.Log("方法2:" + obj.GetType().GetInterfaces().Contains(typeof(IActionForLicenseCheck)));
        #endregion
}

返回指定游戏对象的指定接口

    /// <summary>
    /// 返回指定游戏对象上是否存在指定的接口
    /// </summary>
    /// <typeparam name="Interface">指定的接口</typeparam>
    /// <param name="Go">指定的游戏对象</param>
    /// <returns>返回接口</returns>
    public static Interface GetInterface<Interface>(GameObject Go) where Interface : class
    {
        return Go.GetComponent(typeof(Interface)) as Interface;
    }
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;

public class TestReference : MonoBehaviour
{
    void testlinq()
    {
        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(ISecurity))))
            .ToArray();
    }

    public static IEnumerable<Type> GetType(Type interfaceType)
    {
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach (var type in assembly.GetTypes())
            {
                foreach (var t in type.GetInterfaces())
                {
                    if (t == interfaceType)
                    {
                        yield return type;
                        break;
                    }
                }
            }
        }
    }
}

internal interface ISecurity
{
}

参考:
Unity反射机制的理解
Unity3D架构之第一弹 《善用接口》
[Unity c#]c#中的反射 - Lewis.Xiaoa - 博客园
怎么通过反射获取所有继承了某一接口的类
怎么判断某个类是否继承了某个接口?-CSDN论坛
判断一个类是否继承于指定类或是否实现了指定接口
通过反射获取系统中所有继承了某接口的类

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一:什么是协同程序? 在主线程运行的同时开启另一段逻辑处理,来协助当前程序的执行,协程很像多线程,但是不是多线程,...
    胤醚貔貅阅读 2,110评论 0 13
  • 一:什么是协同程序? 答:在主线程运行时同时开启另一段逻辑处理,来协助当前程序的执行。换句话说,开启协程就是开启一...
    好怕怕阅读 3,950评论 2 23
  • 更新:【面试题含答案】http://bbs.9ria.com/thread-288394-1-1.html 高频问...
    好怕怕阅读 4,826评论 3 52
  • 这个是我刚刚整理出的Unity面试题,为了帮助大家面试,同时帮助大家更好地复习Unity知识点,如果大家发现有什么...
    dingz阅读 626评论 0 0
  • 转自:https://blog.csdn.net/dingxiaowei2013/article/details/...
    豆铮阅读 1,310评论 0 2