c# - 如何实例化 DataReceivedEventArgs 或者能够用数据填充它?

标签 c# .net process

我正在启动一个进程并重定向错误流以便能够解析它并了解发生了什么。我是这样做的:

_proc.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);

其中 NetErrorDataHandler 具有以下签名:

private void NetErrorDataHandler(object sendingProcess, DataReceivedEventArgs errLine)

到目前为止,我必须使用 DataReceivedEventArgs,但我不确定如何测试它。目前我正在运行我正在使用的过程。你不能用额外的数据创建 DataReceivedEventArgs 的实例,那么我该如何克服这个障碍呢?我现在看到如何做到这一点的唯一方法是创建一个可以为我完成工作的流程。但是,这不是用于测试目的的最佳选择。

最佳答案

我刚刚发现可以使用内部构造函数创建对象并设置内部字段。显然,这是不鼓励的,但它适用于短期模拟。这是一个例子:

    private DataReceivedEventArgs CreateMockDataReceivedEventArgs(string TestData)
    {

        if (String.IsNullOrEmpty(TestData))
            throw new ArgumentException("Data is null or empty.", "Data");

        DataReceivedEventArgs MockEventArgs =
            (DataReceivedEventArgs)System.Runtime.Serialization.FormatterServices
             .GetUninitializedObject(typeof(DataReceivedEventArgs));

        FieldInfo[] EventFields = typeof(DataReceivedEventArgs)
            .GetFields(
                BindingFlags.NonPublic |
                BindingFlags.Instance |
                BindingFlags.DeclaredOnly);

        if (EventFields.Count() > 0)
        {
            EventFields[0].SetValue(MockEventArgs, TestData);
        }
        else
        {
            throw new ApplicationException(
                "Failed to find _data field!");
        }

        return MockEventArgs;

    }

这样使用:

DataReceivedEventArgs TestEventArgs = CreateMockDataReceivedEventArgs("Test");

...这需要一些研究,我认为这是不可能的:-)

关于c# - 如何实例化 DataReceivedEventArgs 或者能够用数据填充它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354308/

相关文章:

.net - 在单独的进程中运行 .net 代码

C#/.Net 启动进程,退出代码为 -2146234327

c# - 单例类继承

c# - LINQ to XML - 从文件加载 XML 片段

c# - 从列表中的所有项目中获取特定属性

c# - 如何在 .NET 3.5 中重用线程

windows - 为什么我不能在 Rust 中将 `Stdio::piped()` 与 windows `cmd.exe` 一起使用?

C# Entity Framework (.Net Core)验证(服务器端)如何?

c# - 使用调用构造函数的静态方法是否有任何好处(语义或其他)?

c# - 遍历 List 并回顾性添加到类属性