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

查看:17
本文介绍了构造函数作为委托 - 在 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 值传递,而无需键入:

Is it possible to pass the constructor directly as a FooGenerator value, without having to type:

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天全站免登陆