在C#中,如何使用反射访问花括号构造函数? [英] In C#, how to access curly brace constructor using reflection?

查看:62
本文介绍了在C#中,如何使用反射访问花括号构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我们现在可以使用花括号构造函数构造新对象,即

In C# we can now construct new objects using the curly brace constructor, i.e.

class Person {
   readonly string FirstName {get; set;}
   readonly string LastName {get; set;}
}

new Person { FirstName = "Bob", LastName = "smith" }

我需要使用反射来构造该对象,但是如果将这些成员变量标记为只读,则只能在构造函数中设置它们,并且只有花括号构造函数可用。有什么方法可以使用反射访问花括号样式的构造函数?谢谢。

I need to construct this object using reflection, but if these member variables are marked readonly, I can only set them in the constructor, and there is only the curly-brace constructor available. Is there some way I can access the curly-brace-style constructor using reflection? Thanks.

推荐答案

首先,不能使用 readonly 关键字。他们只能具有非公共的setter方法 *)

First, properties cannot be marked read-only with the readonly keyword. They can only have non-public setter methods*).

第二,没有大括号构造器之类的东西。它只是语法糖(一种捷径),用于以下语句:

Second, there's no such thing as a "curly brace constructor". It's just a syntactic sugar (a shortcut) for a set of statements like this:

Person p = new Person();  // standard parameterless constructor is called
p.FirstName = "Bob";
p.LastName = "Smith";

请注意,您也可以使用带参数的构造函数:

Note that you could also use a constructor with parameters:

new Person(1, 2, 3) { FirstName = "Bob", LastName = "Smith" }

得到的翻译为:

Person p = new Person(1, 2, 3);
p.FirstName = "Bob";
p.LastName = "Smith";






关于反射:构造一个新实例并初始化它与 new Person {FirstName = Bob,LastName = Smith} 示例中的方式相同,您必须:


Regarding reflection: To construct a new instance and initialize it in the same way as in the new Person { FirstName = "Bob", LastName = "Smith" } example you have to:


  1. 检索构造函数(请参见 Type.GetConstructor ),将其称为,使用 Activator.CreateInstance 实例化类型,

  2. 检索 FirstName 属性(请参阅 Type.GetProperty ),

  3. 设置它(请参阅 PropertyInfo.SetValue ),

  4. LastName

  1. retrieve the constructor (see Type.GetConstructor) and call it or use Activator.CreateInstance to instantiate the type,
  2. retrieve the FirstName property (see Type.GetProperty),
  3. set it (see PropertyInfo.SetValue),
  4. repeat (2) and (3) for LastName.






*)更新: C#9将(截至2020年5月)引入init -only属性,相当于 readonly 字段,仅允许在对象初始化期间进行属性分配(即在构造函数或对象初始化程序中)。


*) Update: C# 9 will (as of May 2020) introduce init-only properties, which will be the equivalent of readonly fields, allowing property assignment during object initialization only (i.e. in the constructor or in an object initializer).

这篇关于在C#中,如何使用反射访问花括号构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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