首页 > 解决方案 > 如何创建具有私有类型参数和返回类型的快速调用委托,加速 DynamicInvoke

问题描述

我正在努力创建对 private 的调用ImmutableDictionary.Add,这使我能够利用KeyCollisionBehavior更精细的控制(该Add方法仅在键和值不同时抛出,我需要它总是抛出)。

我可以通过基本反射到达我想要的位置,但是,调用InvokeonMethodInfoDynamicInvoke委托的开销很大(事实上,每次调用的时间几乎增加了三倍,这在我的场景中太重要了)。

我需要调用的函数的签名:

/// call property Origin, this returns a private MutationInput<,>
private MutationInput<TKey, TValue> Origin {get; }

/// call ImmutableDictionary<,>.Add, this takes MutationInput<,> and returns private MutationResult<,>
private static MutationResult<TKey, TValue> Add(TKey key, TValue value, KeyCollisionBehavior<TKey, TValue> behavior, MutationInput<TKey, TValue> origin);

/// then call MutationResult<,>.Finalize
internal ImmutableDictionary<TKey, TValue> Finalize(ImmutableDictionary<TKey, TValue> priorMap);

这里的挑战是我需要传递一个私有类型,并且私有类型是签名的一部分。

通常,在调用 之后CreateDelegate,您可以简单地将其转换为 a Func<X, Y, Z>,这会提供近乎直接的调用速度。Func<,>但是如果泛型类型是私有的和/或在编译时不知道,我不知道如何创建。使用object不起作用,会在演员表上产生运行时异常。

这是我目前拥有的代码的缩短版本(删除了很​​多 try/catch 和检查)。这有效:

/// Copy of enum type from Github source of ImmutableDictionary
type KeyCollisionBehavior =
    /// Sets the value for the given key, even if that overwrites an existing value.
    | SetValue = 0
    /// Skips the mutating operation if a key conflict is detected.
    | Skip = 1
    /// Throw an exception if the key already exists with a different value.
    | ThrowIfValueDifferent = 2
    /// Throw an exception if the key already exists regardless of its value.
    | ThrowAlways = 3

/// Simple wrapper DU to add type safety
type MutationInputWrapper = 
    /// Wraps the type ImmutableDictionary<K, V>.MutationInput, required as 4th param in the internal Add#4 method
    | MutationInput of obj

/// Simple wrapper to add type-safety
type MutationResultWrapper =
    /// Wraps the type ImmutableDictionary<K, V>.MutationResult, which is the result of an internal Add#4 operation
    | MutationResult of obj

/// Type abbreviation
type BclImmDict<'Key, 'Value> = System.Collections.Immutable.ImmutableDictionary<'Key, 'Value>

/// Private extensions to ImmutableDictionary
type ImmutableDictionary<'Key, 'Value>() =
    static let dicType = typeof<System.Collections.Immutable.ImmutableDictionary<'Key, 'Value>>
    static let addMethod = dicType.GetMethod("Add", BindingFlags.NonPublic ||| BindingFlags.Static)
    static let addMethodDelegate = 
        let parameters = addMethod.GetParameters() |> Array.map (fun p -> p.ParameterType)
        let funType = 
            typedefof<Func<_, _, _, _, _>>.MakeGenericType [|
                parameters.[0]
                parameters.[1]
                parameters.[2]
                parameters.[3]
                addMethod.ReturnType
            |]
        Delegate.CreateDelegate(funType, addMethod) // here one would normally cast to Func<X, Y...>

    static let mutationResultFinalizeMethod = 
        if not(isNull addMethod) && not(isNull(addMethod.ReturnParameter)) then
            /// Nested private type MutationResult, for simplicity taken from the return-param type of ImmutableDictionary.Add#4
            let mutationResultType = addMethod.ReturnParameter.ParameterType
            if not(isNull mutationResultType) then
                mutationResultType.GetMethod("Finalize", BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.DeclaredOnly)
            else
                null
        else
            null

    /// System.Collections.Immutable.ImmutableDictionary.get_Origin  // of valuetype ImmutableDictionary<,>.MutationInput<,>
    static let getOrigin = dicType.GetProperty("Origin", BindingFlags.NonPublic ||| BindingFlags.Instance)

    /// Calls private member ImmutableDictionary<,>.Add(key, value, behavior, origin), through reflection
    static member private refl_Add(key: 'Key, value: 'Value, behavior: KeyCollisionBehavior, MutationInput origin) =
        // use Invoke or DynamicInvoke makes little difference.
        //addMethod.Invoke(null, [|key; value; behavior; origin|])
        addMethodDelegate.DynamicInvoke([|box key; box value; box <| int behavior; origin|])
        |> MutationResult

    /// Gets the "origin" of an ImmutableDictionary, by calling the private property get_Origin
    static member private refl_GetOrigin(this: BclImmDict<'Key, 'Value>) =
        getOrigin.GetValue this
        |> MutationInput

    /// Finalizes the result by taking the (internal) MutationResult and returning a new non-mutational dictionary
    static member private refl_Finalize(MutationResult mutationResult, map: BclImmDict<'Key, 'Value>) =
        mutationResultFinalizeMethod.Invoke(mutationResult, [|map|])
        :?> BclImmDict<'Key, 'Value>

    /// Actual Add, with added control through CollisionBehavior
    static member InternalAddAndFinalize(key: 'Key, value: 'Value, behavior, thisMap) =
        let origin = ImmutableDictionary.refl_GetOrigin(thisMap)
        let mutationResult = ImmutableDictionary.refl_Add(key, value, behavior, origin)
        let finalizedMap = ImmutableDictionary.refl_Finalize(mutationResult, thisMap)
        finalizedMap

我意识到上面的代码是用 F# 编写的,但是如果你知道如何在 C# 中解决这个问题,我可以将你的答案翻译成我喜欢的目标语言。

标签: c#reflectionf#delegatesimmutable-collections

解决方案


我认为你过于复杂了。从备注

如果给定的键/值对已经存在于字典中,则返回字典的现有实例。

Add因此,我们可以通过查看该方法是否返回相同的字典引用来判断给定的键/值是否已经存在于字典中。

在 C# 中:

public static ImmutableDictionary<TKey, TValue> AddAndThrowIfAlreadyPresent<TKey, TValue>(
    ImmutableDictionary<TKey, TValue> dict,
    TKey key,
    TValue value)
{
    // null checks, etc
    var newDict = dict.Add(key, value);
    if (newDict == dict)
        throw new ArgumentException($"An element with the same key and value already exists. Key: {key}");
    return newDict;
}

推荐阅读