Yod*_*dah 5 c# reflection inheritance
我创建了一个这样的类型:
TypeBuilder tb = moduleBuilder.DefineType(myname, TypeAttributes.Class |
TypeAttributes.Public, typeof(BaseClass), new Type[] { typeof(ImyInterface) });
Run Code Online (Sandbox Code Playgroud)
然后为构造函数,方法等提供了大量的生成代码.当我开始使用该类时,我发现了一些奇怪的东西.我想检查我创建的类型'myname'是否真的实现了ImyInterface.我希望以下两个语句都返回true:
// t is Type 'myName'
Type baseInterface = t.GetInterface(typeof(ImyInterface).name);
if (baseType != null)
{
// this is actually true, as I expected
}
if (typeof(ImyInterface).isAssignableFrom(t))
{
// the if clause is false, but I don't have a clue why??
}
Run Code Online (Sandbox Code Playgroud)
所以我创建了一个实现ImyInterface的类,但它不能分配给ImyInterface类型的对象,我错过了什么?
顺便说一句,没有涉及泛型,接口只是测试概念的基本方法:
public interface ITestInterface
{
int CalcSquaredInteger(int number);
}
Run Code Online (Sandbox Code Playgroud)
我终于发现我错过了什么:每当您检查在不同项目/程序集中定义的类型和接口之间的类型兼容性和可分配性时,请确保所有项目都经过签名并强命名!否则,GetInterface 方法将起作用,因为它只是比较名称。但.net 不会在类型之间分配。