Delegate for an Actionlt; ref T1, T2gt;(代表一个动作参考 T1,T2)
问题描述
我正在尝试创建一个采用 ref 参数的静态方法的委托.请不要问我为什么要做这样的 cockamamie 事情.这都是学习 .Net、C# 和反射如何工作以及如何优化它的一部分.
I'm trying to create a delegate of a static method which takes a ref argument. Please don't ask why I'm doing such a cockamamie thing. It's all part of learning how .Net, C#, and reflection work and how to optimize it.
我的代码是:
public struct DataRow
{
private double t;
static public void Cram_T(ref DataRow dr, double a_t)
{
dr.t = a_t;
}
}
''''
Type myType = typeof(DataRow);
MethodInfo my_Cram_T_Method = myType.GetMethod("Cram_T");
var myCram_T_Delegate =
Delegate.CreateDelegate(typeof(Action<DataRow, Double>),
my_Cram_T_Method)
as Action<DataRow, Double>;
这给了我一个绑定错误,因为(我认为)通用操作与方法不匹配.
This gives me a binding error because (I think) the generic action doesn't match the method.
在监视窗口中检查 Cram_T_Method 的值给出
Inspecting the value of Cram_T_Method in the watch window gives
{Void Cram_T(DataRow ByRef, Double)}
然后我尝试在 Action 中使用 ref 关键字:
I then tried using the ref keyword in the Action:
var myCram_T_Delegate =
Delegate.CreateDelegate(typeof(Action<ref DataRow, Double>),
my_Cram_T_Method)
as Action<ref DataRow, Double>;
但这不会编译.C# 编译器在标记ref"处窒息.
But this won't compile. The C# compiler chokes at the token "ref".
创建此委托的正确方法是什么?
What is the right way to create this delegate?
推荐答案
创建自己的委托类型:
delegate void MyAction(ref DataRow dataRow, double doubleValue);
并使用 MyAction 代替 Action<ref DataRow, Double> - 正如您所指出的那样,它不会编译.
And use MyAction in place of Action<ref DataRow, Double> -- which, as you've noted, doesn't compile.
这篇关于代表一个动作<参考 T1,T2>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:代表一个动作<参考 T1,T2>
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
