5

我正在使用 C#/.NET 4.0 和提供以下功能的协议缓冲区库 (protobuf-net)。

public static class Serializer {
    public static void Serialize<T>(Stream destination, T instance);
    public static void Serialize<T>(SerializationInfo info, T instance);
    public static void Serialize<T>(XmlWriter writer, T instance);
    public static void Serialize<T>(SerializationInfo info, StreamingContext context, T instance);
    public static T Deserialize<T>(Stream source);
}

我需要用非通用等价物包装其中两个调用。具体来说,我想要

void SerializeReflection(Stream destination, object instance);
object DeserializeReflection(Stream source, Type type);

Serializer这只是在运行时调用相应的通用成员。我已经获得了DeserializeReflection使用以下代码的方法:

public static object DeserializeReflection(Stream stream, Type type)
{
    return typeof(Serializer)
        .GetMethod("Deserialize")
        .MakeGenericMethod(type)
        .Invoke(null, new object[] { stream });
}

SerializeReflection方法是给我带来麻烦的原因。我首先尝试了以下代码:

public static void SerializeReflection(Stream stream, object instance)
{
    typeof(Serializer)
        .GetMethod("Serialize")
        .MakeGenericMethod(instance.GetType())
        .Invoke(null, new object[] { stream, instance });
}

typeof(Serializer)问题是和之间的部分.Invoke(...)不起作用。调用GetMethod("Serialize")让我得到一个AmbiguousMatchException,因为有四个名为“ Serialize.”的方法。

然后我尝试使用GetMethod需要数组的重载System.Type来解析绑定:

GetMethod("Serialize", new[] { typeof(Stream), instance.GetType() })

但这只是造成的结果GetMethod null

如何使用反射来获取MethodInfofor void Serializer.Serialize<T>(Stream, T),在T哪里instance.GetType()

4

2 回答 2

4

尝试使用下一个代码片段来查看它是否满足您的需求。它创建了一个封闭类型的方法实例public static void Serialize<T>(Stream destination, T instance)。在这种情况下,它选择第一个方法Stream作为参数,但您可以将此谓词更改method.GetParameters().Any(par => par.ParameterType == typeof(Stream))为您想要的任何内容

public static object DeserializeReflection(Stream stream, object instance)
{
   return typeof(Serializer)
        .GetMethods()
        .First(method => method.Name == "Serialize" && method.GetParameters().Any(par => par.ParameterType == typeof(Stream)))
        .MakeGenericMethod(instance.GetType())
        .Invoke(null, new object[] { stream, instance });
}
于 2013-01-08T19:27:04.253 回答
2

对于这类事情,我经常使用这样的辅助方法

public static MethodInfo MakeGenericMethod<TSourceType>(Type genericArgument, string methodName, Type[] parameterTypes, params int[] indexesWhereParameterIsTheGenericArgument)
{
    //Get the type of the thing we're looking for the method on
    var sourceType = typeof (TSourceType);
    //Get all the methods that match the default binding flags
    var allMethods = sourceType.GetMethods();
    //Get all the methods with the same names
    var candidates = allMethods.Where(x => x.Name == methodName);

    //Find the appropriate method from the set of candidates
    foreach (var candidate in candidates)
    {
        //Look for methods with the same number of parameters and same types 
        //   of parameters (excepting for ones that have been marked as 
        //   replaceable by the generic parameter)
        var parameters = candidate.GetParameters();
        var successfulMatch = parameters.Length == parameterTypes.Length;

        if (successfulMatch)
        {
            for (var i = 0; i < parameters.Length; ++i)
            {
                successfulMatch &= parameterTypes[i] == parameters[i].ParameterType || indexesWhereParameterIsTheGenericArgument.Contains(i);
            }
        }

        //If all the parameters were validated, make the generic method and return it
        if (successfulMatch)
        {
            return candidate.MakeGenericMethod(genericArgument);
        }
    }

    //We couldn't find a suitable candidate, return null
    return null;
}

要使用它,你会做

var serializeMethod = MakeGenericMethod<Serializer>(instance.GetType(), "Serialize", new[]{typeof(stream), typeof(object)}, 1);
于 2013-01-08T19:29:44.343 回答