c# - 如何创建具有私有类型参数和返回类型的快速调用委托,加速 DynamicInvoke
问题描述
我正在努力创建对 private 的调用ImmutableDictionary.Add
,这使我能够利用KeyCollisionBehavior
更精细的控制(该Add
方法仅在键和值不同时抛出,我需要它总是抛出)。
我可以通过基本反射到达我想要的位置,但是,调用Invoke
onMethodInfo
或DynamicInvoke
委托的开销很大(事实上,每次调用的时间几乎增加了三倍,这在我的场景中太重要了)。
我需要调用的函数的签名:
/// 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# 中解决这个问题,我可以将你的答案翻译成我喜欢的目标语言。
解决方案
我认为你过于复杂了。从备注:
如果给定的键/值对已经存在于字典中,则返回字典的现有实例。
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;
}
推荐阅读
- conditional-statements - AMPL – 如果特定变量处于活动状态(多个条件?),则强制一个变量
- bash - 根据连续输出流的内容发出命令
- c - sbrk(0) 并不总是返回相同的值
- javascript - 如何使用 Firebase 验证登录凭据?
- python - Python - 处理不是 2 倍数的二进制数据的优雅方式
- mysql - 如何在 MySQL 数据库中设置州和城市之间的关系?
- python - Python3:从新数据源更新散景数据表
- reactjs - 将管理员(用户名和密码)保存到反应应用程序中是否安全
- javascript - 是否可以访问在 wdio.conf 中声明的变量?
- python - 带有多索引和 parse_date 的 pandas read_excel;如何?