构造函数作为一个委托 - 这可能在C#中? [英] a constructor as a delegate - is it possible in C#?

查看:168
本文介绍了构造函数作为一个委托 - 这可能在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类象下面这样:

I have a class like below:

class Foo
{
  public Foo(int x) { ... }
}

和我需要通过一定的方法的委托是这样的:

and I need to pass to a certain method a delegate like this:

delegate Foo FooGenerator(int x);

是否有可能直接传递构造为 FooGenerator 价值,而不必键入:

delegate(int x) { return new Foo(x); }

编辑:我私人使用的,这个问题指的是.NET 2.0,但提示/为3.0+反应是欢迎,以及

For my personal use, the question refers to .NET 2.0, but hints/responses for 3.0+ are welcome as well.

推荐答案

不,在CLR不允许绑定委托给 ConstructorInfo

Nope, the CLR does not allow binding delegates to ConstructorInfo.

您可以不过才创建自己的:

You can however just create your own:

static T Make<T>(Action<T> init) where T : new()
{
  var t = new T();
  init(t);
  return t;
}

用法

var t = Make<Foo>( x => { x.Bar = "bar"; x.Baz = 1; });

这篇关于构造函数作为一个委托 - 这可能在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆