小编Alf*_*ort的帖子

Action和Func <T>都没有显式转换

我有一个类必须接收方法,以便调用它们以及执行其他执行.这些方法必须多次使用,并且对于许多不同的用户,因此越简单越好.

为了解决这个问题,我有两种方法:

    void Receive(Action func)
    {
        // Do some things.
        func();
    }

    T Receive<T>(Func<T> func)
    {
        // Do some things.
        return func();
    }
Run Code Online (Sandbox Code Playgroud)

(实际上我有34种方法可以接收任何不同的Action或Func定义.)

然后,我希望能够将任何方法作为参数传递给Receive函数,以便能够执行以下操作:

    void Test()
    {
        Receive(A);
        Receive(B);
    }

    void A()
    {
    }

    int B()
    {
        return 0;
    }
Run Code Online (Sandbox Code Playgroud)

就像这样,它在Receive(B)中给出了一个错误:

The call is ambiguous between the following methods or properties: 'Class1.Receive(System.Action)' and 'Class1.Receive<int>(System.Func<int>)'
Run Code Online (Sandbox Code Playgroud)

好的,签名是相同的(虽然如果我不使用这些方法,则不会显示错误).

如果我删除Receive(Action)方法,我会收到Receive(A)以下错误:

The type arguments for method 'Class1.Receive<T>(System.Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Run Code Online (Sandbox Code Playgroud)

但是我在这种情况下的类型是无效的,禁止将它用作通用参数.

那么,有没有办法让我的Receive方法不使用任何显式的Action或Func?

c# generics signature void

7
推荐指数
1
解决办法
892
查看次数

使用Invoke方法从外部线程关闭表单

我必须从线程关闭Form,并且正在使用Form的Invoke方法调用Close()方法。

问题是,关闭时将处理该窗体,并且我收到一条InvalidOperationExecption消息:“在创建窗口句柄之前,无法在控件上调用Invoke或BeginInvoke”。

仅当在Close方法中使用“ Step Into”进行调试时,我才遇到此异常,但是我不想冒险在正常运行时可能出现错误。

这是重现它的示例代码:

 private void Form1_Load(object sender, EventArgs e)
 {
     Thread thread = new Thread(CloseForm);
     thread.Start();
 }

 private void CloseForm()
 {
     this.Invoke(new EventHandler(
         delegate
         {
             Close(); // Entering with a "Step Into" here it crashes.
         } 
     ));
 }
Run Code Online (Sandbox Code Playgroud)

表单以自动生成的表单代码(我不希望对其进行修改)处理:

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }
Run Code Online (Sandbox Code Playgroud)

如果有人可以为我提供这种方法或其他方法来关闭另一个线程中的表单,我将不胜感激。

c# multithreading invoke winforms

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

generics ×1

invoke ×1

multithreading ×1

signature ×1

void ×1

winforms ×1