Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 不确定要在事件订阅方法中使用的类型_C#_Action - Fatal编程技术网

C# 不确定要在事件订阅方法中使用的类型

C# 不确定要在事件订阅方法中使用的类型,c#,action,C#,Action,我试图创建一个通用函数,它应该描述windows事件日志中不同内部方法的一些线程。于是我写道: void SubScribeToEventLogEvent(string EventLog,int EventID,string Source, Action named ="myMethod") { string query = "*[System/Level=8] and [System/EventID=" +EventID.ToString()+"]"; EventLogQue

我试图创建一个通用函数,它应该描述windows事件日志中不同内部方法的一些线程。于是我写道:

void SubScribeToEventLogEvent(string EventLog,int EventID,string Source, Action named ="myMethod")
{
    string query = "*[System/Level=8] and [System/EventID=" +EventID.ToString()+"]";

    EventLogQuery subscriptionQuery = new EventLogQuery(EventLog, PathType.LogName, "*[System/Level=8]");
    EventLogWatcher watcher = new EventLogWatcher(subscriptionQuery);
    watcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(named);
    watcher.Enabled = true;
}
这样我就可以简单地写

SubScribeToEventLogEvent(EventlogName,200,myMethod)

然而,它不工作,我在.NET4.0中编写代码,我相信动作是做这些事情的保留方法。但是我得到了一个错误(在代码的第一行中,红线已经在命名下):

SubScribeToEventLogEvent(string EventLog,int EventID,string Source,Action name=“myMethod”)


显然,它不能被分配一个字符串值(但还有什么?),如果我删除字符串值,它在Eventhandler函数中仍然无法识别。

您是否有名为
Action
的用户定义类型?否则,如果您谈论的是动作委托
Action
实际上不是字符串,就会感到困惑:是的,
Action name=“myMethod”
绝对不正确。不知道你为什么要这么做。“命名”的类型应为
EventHandler
,并且(可能)应该可以工作。不能仅使用方法的名称将子对象添加到事件。您必须拥有一个实例并使用反射来获得该实例方法的委托。@will,嗯,我的意图是使用一个方法的名称进行sub,是否有其他方法可以做到这一点?“named”应该是
EventHandler
类型,您可以简单地将该方法传入并+=
named
直接传递给事件。
private void myMethod(object obj,EventRecordWrittenEventArgs arg)
{
    //do something
    if (arg.EventRecord != null)
    {
        MessageBox.Show(arg.EventRecord.Id.ToString() + arg.EventRecord.FormatDescription());
        Console.WriteLine("Received event {0} from the subscription.", arg.EventRecord.Id);
        Console.WriteLine("Description: {0}", arg.EventRecord.FormatDescription());
    }
    else
    {
        Console.WriteLine("The event instance was null.");
    }
}