我的项目中有一个派生类的泛型类.
public class GenericClass<T> : GenericInterface<T>
{
}
public class Test : GenericClass<SomeType>
{
}
Run Code Online (Sandbox Code Playgroud)
有没有办法找出一个Type对象是否来自GenericClass?
t.IsSubclassOf(typeof(GenericClass<>))
Run Code Online (Sandbox Code Playgroud)
不起作用.
假设以下类型定义:
public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
Run Code Online (Sandbox Code Playgroud)
当只有受损的类型可用时,如何确定类型是否Foo实现了通用接口IBar<T>?
我正在研究C#中的游戏引擎.我正在研究的课程被称为CEntityRegistry,它的工作是跟踪CEntity游戏中的许多实例.我的目标是能够CEntityRegistry使用给定的类型查询,并获得每种CEntity类型的列表.
因此,我想做的是维护一张地图:
private IDictionary<Type, HashSet<CEntity>> m_TypeToEntitySet;
Run Code Online (Sandbox Code Playgroud)
并因此更新注册表:
private void m_UpdateEntityList()
{
foreach (CEntity theEntity in m_EntitiesToRemove.dequeueAll())
{
foreach (HashSet<CEntity> set in m_TypeToEntitySet.Values)
{
if (set.Contains(theEntity))
set.Remove(theEntity);
}
}
foreach (CEntity theEntity in m_EntitiesToAdd.dequeueAll())
{
Type entityType = theEntity.GetType();
foreach (Type baseClass in entityType.GetAllBaseClassesAndInterfaces())
m_TypeToEntitySet[baseClass].Add(theEntity);
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是没有功能Type.GetAllBaseClassesAndInterfaces- 我将如何写它?
我需要测试一个值是否是通用基类的实例,而又不知道通用类型参数。使用MSDN示例作为示例的基础,这是我要完成的任务:
using System;
public class Class1<T> { }
public class DerivedC1 : Class1<int> { }
class IsSubclassTest
{
public static void Main()
{
Console.WriteLine(
"DerivedC1 subclass of Class1: {0}",
typeof(DerivedC1).IsSubclassOf(typeof(Class1<>)) // <- Here.
);
}
}
Run Code Online (Sandbox Code Playgroud)
尽管从语法上讲这是正确的,但始终会产生错误。如果删除通用类型参数,它将按预期工作(返回true)。
如何在不知道类通用类型参数的情况下,测试类类型是否是通用基类的子类?