C# - 类与类之间的继承关系判断

发布于:2024-03-03 ⋅ 阅读:(64) ⋅ 点赞:(0)

Type.IsSubclassof(Type type)

作用:用来确定 一个类是否派生自另一个类/ValueType/Enum/委托

不能用于确定:接口是派生自另一个接口,还是类实现接口

class A{}
class B : A{}

A a;
B b;

var boo = b.GetType().IsSubclassOf(typeof(A)) // ture

Type.IsAssignableFrom(Type type)

作用:用于确定 接口是派生自另一个接口,还是类实现接口

class A{}
class B : A{}

A a;
B b;

var boo = a.GetType().IsAssignable(typeof(b)) // ture

自定义关系判断


		/// <summary>
		/// 兼顾类与类 类与接口 接口与接口
		/// </summary>
		/// <param name="targetType">目标子类型</param>
		/// <param name="targetBaseType">目标基类型</param>
		/// <returns></returns>
		public static bool IsAssignableType(Type targetType, Type targetBaseType)
		{
			return targetType?.IsSubclassOf(targetBaseType) != false || targetBaseType?.IsAssignableFrom(targetType) != false;
		}
interface IData { }
class A : IData { }
class B : A { }		

var boo = FEditorUtility.IsAssignableType(typeof(B), typeof(A));
Debug.Log(boo);//true
boo = typeof(B).IsSubclassOf(typeof(A));
Debug.Log(boo);//true
boo = typeof(B).IsSubclassOf(typeof(IData));
Debug.Log(boo);//false
boo = typeof(A).IsAssignableFrom(typeof(B));
Debug.Log(boo);//true
boo = typeof(IData).IsAssignableFrom(typeof(B));
Debug.Log(boo);//true


网站公告

今日签到

点亮在社区的每一天
去签到