gpt4 book ai didi

c# - 如何创建具有参数和私有(private)类型返回类型的快速调用委托(delegate),加速 DynamicInvoke

转载 作者:行者123 更新时间:2023-12-03 20:38:08 25 4
gpt4 key购买 nike

我正在努力创建对私有(private)的调用 ImmutableDictionary.Add ,这让我可以利用 KeyCollisionBehavior为了更好地控制(Add 方法仅在键和值不同时抛出,我需要它始终抛出)。

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

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

/// 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);

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

通常,在调用 CreateDelegate 之后, 你可以简单地将它转换为 Func<X, Y, Z>这提供了近乎直接的调用速度。但我不知道如何创建 Func<,>如果泛型类型是私有(private)的和/或在编译时未知。使用 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# 中解决这个问题,我可以毫无问题地将您的答案翻译成我首选的目标语言。

最佳答案

我认为你过于复杂了。来自 the Remarks :

If the given key/value pair already exists in the dictionary, the existing instance of the dictionary is returned.

所以我们可以通过查看 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;
}

关于c# - 如何创建具有参数和私有(private)类型返回类型的快速调用委托(delegate),加速 DynamicInvoke,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59845974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com