C#多级泛型结合继承/多态的容器类实现(Unity场景)
问题与解决方案
卡在这个问题上很久了,想问问有没有其他实现方式,或是我遗漏了什么步骤。
基础类定义
public class StartType0<T1, T2> where T1 : StartType1 where T2 : StartType2 {} public class StartType1 {} public class StartType2 {} public class EndType0 : StartType0<EndType1, EndType2> {} public class EndType1 : StartType1 {} public class EndType2 : StartType2 {}
我想要创建一个容器类来存储EndType0类型的数组,用于在Unity中为StartType0类绘制通用自定义属性抽屉。
尝试过多种方法都遇到问题:
- 传入所有泛型参数时,无法将
StartType0转换为EndType0; - 将
EndType0作为泛型参数传入时,因多态支持问题导致异常; - 理想的单泛型参数容器类写法无法正常工作。
编辑1
按照@JohnathanBarclay的建议修改后,代码可编译但无法在Unity编辑器中正常显示:
public class StartType0<out T1, out T2> where T1 : StartType1, IStartType1 where T2 : StartType2, IStartType2 {} public interface IStartType1 {} public class StartType1 : IStartType1 {} public interface IStartType2 {} public class StartType2 : IStartType2 {} public class EndType0 : StartType0<EndType1, EndType2> {} public class EndType1 : StartType1 {} public class EndType2 : StartType2 {}
编辑2
经过调试,得到了目前的理想实现方案,可支持自定义属性抽屉并使用Activator操作泛型类型:
public interface IStartType0<out T1, out T2> where T1 : IStartType1<StartType1> where T2 : IStartType2<StartType2> {} public class StartType0<T1, T2> : IStartType0<T1, T2> where T1 : IStartType1<StartType1> where T2 : IStartType2<StartType2> {} public interface IStartType1<out T> where T : StartType1 {} public class StartType1 : IStartType1<StartType1> {} public interface IStartType2<out T> where T : StartType2 {} public class StartType2 : IStartType2<StartType2> {} public class EndType0 : StartType0<EndType1, EndType2> {} public class EndType1 : StartType1 {} public class EndType2 : StartType2 {} public class TypeContainer<T0, T1, T2> where T0 : IStartType0<T1, T2> where T1 : IStartType1<StartType1> where T2 : IStartType2<StartType2> { public T0[] array = new T0[1]; public TypeContainer() { array[0] = (T0)Activator.CreateInstance(typeof(T0)); } } public class Tester { public TypeContainer<EndType0, EndType1, EndType2> container = new TypeContainer<EndType0, EndType1, EndType2>(); public Tester() { EndType0 instance = container.array[0]; } }
这个方案可以保证基础类型的一致性,支持运行自定义属性抽屉生成自定义检视面板,还能使用Activator处理泛型类型。
内容的提问来源于stack exchange,提问作者Solist
相关产品推荐
相关产品推荐

