【发布时间】:2021-08-15 21:34:30
【问题描述】:
我有一些从与通信总线接口的 DLL 导入的类似 set/get 函数。理想情况下,这些都应该共享一个相同的包装器,做一些错误检查、互斥处理等。下面的代码 sn-p 是它的基本表示。它编译并且所有函数似乎都可以工作,除了 WrappedGet() 不修改引用的变量数据。想法?
static UInt32 common_var = 0;
// Reduce boilerplate by wrapping all calls to the DLL with this
static private bool CommonWrapper<T1>(Action<T1> dll_function_handle, ref T1 data)
{
// Commmon code for mutex handling etc
/// ....
// Call to function handle, sometimes data is in-parameter, other times out-param
dll_function_handle(data);
return true;
}
static private void DllSet(UInt32 data) { common_var = data; }
static public void WrappedSet(UInt32 data) { CommonWrapper<UInt32>((UInt32 a) => DllSet(a), ref data); }
static private void DllGet(ref UInt16 data){ data = 1234; }
// WrappedGet does not modify argument "data" because of the lambda? What to do?
static public void WrappedGet(ref UInt16 data) { CommonWrapper<UInt16>((UInt16 a) => DllGet(ref a), ref data); }
编辑:
这行得通:
static public void WrappedGet(ref UInt16 data)
{
UInt16 local = 0;
CommonWrapper<UInt16>((UInt16) => DllGet(ref local), ref data);
data = local;
}
这有点尴尬,这是正确的做法吗?
【问题讨论】:
-
dll_function_handle是一个Action<>... 因此,它的第一个也是唯一一个参数仅用于输入,并且底层方法执行的任何更改都将丢失。您最好重新考虑CommonWrapper:您可能需要再重载一个接受Func<>委托而不是Action<>委托才能返回结果。 -
使用
Action<>似乎不是问题,请参阅上面的编辑答案。另外,对于真实世界的代码,我使用Func<>。 -
谁能帮我指出为什么我在这篇文章中得到了一个减分?