在.NET Standard / Core中序列化MethodInfo

我正在将库从.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,但是随后我无法反序列化它,而且序列化的对象最终会占用大量内存...

感谢任何建议!

heaventoyou 回答:在.NET Standard / Core中序列化MethodInfo

正如例外所述,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>));
    }
}
本文链接:https://www.f2er.com/3014790.html

大家都在问