我正在使用 Assembly.GetTypes()来获取插件库中定义的所有类型(因此我可以实例化插件实例)。
在特定库上,该方法引发ReflectionTypeLoadException,说:
Type <Type> is attempting to implement an inaccessible interface
谷歌搜索似乎是因为特定的类型实现了非公共接口。实际上它是,但 Type 嵌套在另一个公共类中,声明为私有。
如何避免此异常?
...
使接口公开代码工作。是否有可能定义这种奇怪的行为是一个bug(在Assembly.GetTypes()中)?这意味着库类型无法实现受保护的交互面!
答案 0 :(得分:8)
通过从公共类型中删除受保护的嵌套类型来解决问题。
答案 1 :(得分:2)
我在MessagePack序列化时面临同样的问题。我试图在内部类中实现接口,因此它来自于程序集&#39; MessagePack.Resolvers.DynamicObjectResolver,Version = 0.0.0.0,Culture = neutral,PublicKeyToken = null&#39;正试图实现一个无法访问的界面。&#34; 所以我把它的内部类从它的容器类中取出,在下面的同一个命名空间中是我的前后代码... 前....
using MessagePack;
using System;
namespace ConsoleApp1
{
class CallbackReciever
{
[MessagePackObject]
public class SampleCallback : IMessagePackSerializationCallbackReceiver
{
[Key(0)]
public int Key { get; set; }
public void OnBeforeSerialize()
{
Console.WriteLine("OnBefore");
}
public void OnAfterDeserialize()
{
Console.WriteLine("OnAfter");
}
}
public static void Main()
{
SampleCallback b1 = new SampleCallback { Key = 1 };
Console.WriteLine("Starting serialization");
byte[] data = MessagePackSerializer.Serialize<dynamic>(b1);
foreach (byte b in data)
{
Console.WriteLine(b);
}
SampleCallback temp = MessagePackSerializer.Deserialize<SampleCallback>(data);
Console.WriteLine(MessagePackSerializer.ToJson(temp));
}
}
}
在...
using MessagePack;
using System;
namespace ConsoleApp1
{
[MessagePackObject]
public class SampleCallback : IMessagePackSerializationCallbackReceiver
{
[Key(0)]
public int Key { get; set; }
public void OnBeforeSerialize()
{
Console.WriteLine("OnBefore");
}
public void OnAfterDeserialize()
{
Console.WriteLine("OnAfter");
}
}
class CallbackReciever
{
public static void Main()
{
SampleCallback b1 = new SampleCallback { Key = 1 };
Console.WriteLine("Starting serialization");
byte[] data = MessagePackSerializer.Serialize<dynamic>(b1);
foreach (byte b in data)
{
Console.WriteLine(b);
}
SampleCallback temp = MessagePackSerializer.Deserialize<SampleCallback>(data);
Console.WriteLine(MessagePackSerializer.ToJson(temp));
Console.ReadKey();
}
}
}