【问题标题】:Serialize MethodInfo in .NET Standard/Core在 .NET Standard/Core 中序列化 MethodInfo
【发布时间】:2020-03-24 00:39:53
【问题描述】:

我正在将一个库从 .NET Framework 移植到 .NET Standard 2.0。初始库使用 BinaryFormatter 序列化 MethodInfo 类型的对象。虽然这在 .NET Framework 中没有任何问题,但在 .NET Standard 中会引发异常:

System.Runtime.Serialization.SerializationException:在程序集“System.Private.CoreLib,版本=4.0.0.0,文化=中性,PublicKeyToken=7cec85d7bea7798e”中键入“System.Reflection.RuntimeMethodInfo”未标记为可序列化.

为什么这在 .NET Standard/Core 中不起作用?是否有任何解决方法可以使这成为可能?我尝试使用 Newtonsoft 将其序列化为 JSON,但后来我无法反序列化它,而且序列化的对象最终会占用大量内存...

感谢任何建议!

【问题讨论】:

  • 你为什么要序列化RuntimeMethodInfo
  • 我们有两个系统共享同一个库,其中第一个系统告诉第二个系统调用一个方法。使用 .NET Framework 库,调用只需传递一个 Expression 即可完成同样的事情
  • 那你为什么不使用自己的包含程序集名称、类型名称和方法名称的类? “第二个系统”可以从此类信息中重新创建 RuntimeMethodInfo ... 有一些缓存应该没问题
  • 好点,试试看!

标签: c# serialization .net-core .net-standard-2.0


【解决方案1】:

正如例外所说,MethodInfo 不再是可序列化的,因此您不能使用默认的 BinarySerializer 序列化委托、Actions、Func ....。

查看这个问题了解更多详情和原因:https://github.com/dotnet/corefx/issues/19119

也许这是一种解决方法,它使用反射在序列化后绑定函数:

class Program
{
    [Serializable]
    public class Test
    { 

        [JsonIgnore]
        public Action<string> AFunc { get; set; }

        public string[] AFuncIdentifier { get; set; }
    }

    public static class Methods
    {
        public static void Log(string additional)
        {
            Console.WriteLine(additional);
        }
    }

    static void Main(string[] args)
    {
        var myTest = new Test();
        myTest.AFunc = Methods.Log;
        myTest.AFuncIdentifier = new string[] { myTest.AFunc.Method.DeclaringType.FullName,
            myTest.AFunc.Method.Name };

        var raw = JsonConvert.SerializeObject(myTest);
        var test = JsonConvert.DeserializeObject<Test>(raw);

        RestoreFunc(test);
        test.AFunc("a");
    }

    private static void RestoreFunc(Test test)
    {
        var fIdentifier = test.AFuncIdentifier;
        var t = Assembly.GetExecutingAssembly().GetType(fIdentifier[0]);
        var m = t.GetMethod(fIdentifier[1]);
        test.AFunc = (Action<string>)m.CreateDelegate(typeof(Action<string>));
    }
}

【讨论】:

    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多