gpt4 book ai didi

c# - 如何从 C# 中的 Action 委托(delegate)调用非静态方法

转载 作者:太空狗 更新时间:2023-10-30 01:18:26 26 4
gpt4 key购买 nike

由于我正在为要执行的某些操作编写通用概念,因此我需要在 Action 委托(delegate)中调用一些非静态方法。此外,它们在我的代码中都不是静态的。但是我仍然无法在 Action 定义中调用非静态方法。这是我的代码-

private Dictionary<string, Action<object>> m_dicUndoRedoAction = new Dictionary<string, Action<object>>();
m_dicUndoRedoAction.Add("DeleteClass", DeleteClassFromeNode );

下面是 DeleteClass 的定义

private Action<object> DeleteClassFromeNode =
data =>
{
Tuple<itemType1, itemType2> items = data as Tuple<itemType1, itemType2>;
if (items != null && items.Item2 != null)
{
DeleteClass(items.Item2); // This is my non static method in the same class.
}
};

下面是我如何调用委托(delegate)

private void Undo_Executed(object sender, ExecutedRoutedEventArgs e)
{
object temp;
if (UndoRedoAction.DoUndo(out temp))
{
m_dicUndoRedoAction["DeleteClass"].Invoke(temp);
}
}

正如编译器所说

A field initializer cannot reference the non-static field, method, or property 'DeleteClassFromeNode'

我还查看了 Action 的 MSDN 引用资料文章,但 MS 没有提到 Action 是隐式静态的,还是我走错了路?我还查看了一些来自静态方法的非静态调用,但没有一个能令人满意地解释。如果有人提供其低级解释,我将不胜感激。

On response to Peter explanation

虽然初始化程序在构造函数完成之前运行,但这并不能使其在构造函​​数执行之间触发委托(delegate)。即使您将在 ILDASM 中查找它的汇编代码,它也会将实际操作字段显示为非静态,但将缓存的匿名委托(delegate)对象显示为静态。为什么编译器会出现这种不同的行为?

enter image description here

最佳答案

正如编译器告诉您的那样,禁止在初始化程序中使用非静态成员。这是因为初始化程序在构造函数完成之前运行,因此使用非静态成员不一定安全。

相反,只需在构造函数中执行初始化:

public MyClass()
{
DeleteClassFromeNode = data =>
{
Tuple<itemType1, itemType2> items = data as Tuple<itemType1, itemType2>;
if (items != null && items.Item2 != null)
{
DeleteClass(items.Item2); // This is my non static method in the same class.
}
};

// Other initialization code can go here (or before...whatever is most appropriate)
}

关于c# - 如何从 C# 中的 Action<T> 委托(delegate)调用非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27437965/

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