使用匿名委托返回对象

发布于 2024-10-16 02:46:13 字数 96 浏览 4 评论 0原文

是否可以使用匿名委托返回对象?

像这样:

object b = delegate { return a; };

Is it possible to use an anonymous delegate to return an object?

Something like so:

object b = delegate { return a; };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

断爱 2024-10-23 02:46:13

是的,但只能通过调用它:

Func<object> func = delegate { return a; };
// or Func<object> func = () => a;
object b = func();

当然,以下要简单得多......

object b = a;

在注释中,提到了跨线程异常;这可以按如下方式修复:

如果委托是我们想要从 BG 线程在 UI 线程上运行回来的东西:

object o = null;
MethodInvoker mi = delegate {
    o = someControl.Value; // runs on UI
};
someControl.Invoke(mi);
// now read o

或者相反(在 BG 上运行委托):

object value = someControl.Value;
ThreadPool.QueueUserWorkItem(delegate {
    // can talk safely to "value", but not to someControl
});

Yes, but only by invoking it:

Func<object> func = delegate { return a; };
// or Func<object> func = () => a;
object b = func();

And of course, the following is a lot simpler...

object b = a;

In the comments, cross-thread exceptions are mentioned; this can be fixed as follows:

If the delegate is the thing we want to run back on the UI thread from a BG thread:

object o = null;
MethodInvoker mi = delegate {
    o = someControl.Value; // runs on UI
};
someControl.Invoke(mi);
// now read o

Or the other way around (to run the delegate on a BG):

object value = someControl.Value;
ThreadPool.QueueUserWorkItem(delegate {
    // can talk safely to "value", but not to someControl
});
给不了的爱 2024-10-23 02:46:13

只需在某处声明这些静态函数:

public delegate object AnonymousDelegate();

public static object GetDelegateResult(AnonymousDelegate function)
{
    return function.Invoke();
}

并且在任何地方都可以像这样使用它:

object item = GetDelegateResult(delegate { return "TEST"; });

或者甚至像这样

object item = ((AnonymousDelegate)delegate { return "TEST"; }).Invoke();

Just declare somewhere these static functions:

public delegate object AnonymousDelegate();

public static object GetDelegateResult(AnonymousDelegate function)
{
    return function.Invoke();
}

And anywhere use it as you want like this:

object item = GetDelegateResult(delegate { return "TEST"; });

or even like this

object item = ((AnonymousDelegate)delegate { return "TEST"; }).Invoke();
π浅易 2024-10-23 02:46:13
using System;

public delegate int ReturnedDelegate(string s);

class AnonymousDelegate
{
    static void Main()
    {
        ReturnedDelegate len = delegate(string s)
        {
            return s.Length;
        };
        Console.WriteLine(len("hello world"));
    }
}
using System;

public delegate int ReturnedDelegate(string s);

class AnonymousDelegate
{
    static void Main()
    {
        ReturnedDelegate len = delegate(string s)
        {
            return s.Length;
        };
        Console.WriteLine(len("hello world"));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文