gpt4 book ai didi

c# - 为什么 IsAssignableFrom 和 GetInterface 给出不同的结果

转载 作者:太空狗 更新时间:2023-10-29 23:35:02 24 4
gpt4 key购买 nike

我创建了这样一个类型:

TypeBuilder tb = moduleBuilder.DefineType(myname, TypeAttributes.Class |
TypeAttributes.Public, typeof(BaseClass), new Type[] { typeof(ImyInterface) });

然后是构造函数、方法等的大量生成代码。当我开始使用该类(class)时,我注意到了一些奇怪的事情。我想检查我创建的类型“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??
}

所以我创建了一个实现 ImyInterface 的类,但它不能分配给 ImyInterface 类型的对象,我错过了什么?

顺便说一句,这里不涉及泛型,接口(interface)只是测试概念的基本接口(interface):

public interface ITestInterface
{
int CalcSquaredInteger(int number);
}

最佳答案

我终于发现了我遗漏的东西:每当您检查您在不同项目/程序集中定义的类型和接口(interface)之间的类型兼容性和可分配性时,请确保您的所有项目都已签名并具有强名称!!否则 GetInterface 方法将起作用,因为它只是比较名称。但是 .net 不会在类型之间分配。

关于c# - 为什么 IsAssignableFrom 和 GetInterface 给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3341378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com