In C #, how to access the curly brace constructor using reflection?

In C #, we can now build 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 build this object using reflection, but if these member variables are marked as readonly, I can only set them in the constructor, and only the curly braces constructor exists. Is there a way to access the curly designer using reflection? Thanks.

+4
source share
4 answers

First, properties cannot be read-only with the readonly keyword. They can only have non-public customization methods.

Secondly, there is no such thing as a “braces constructor”. This is just syntactic sugar (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 can also use the constructor with parameters:

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

translates as:

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

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

+23
source

This has nothing to do with the constructor. This is just a short syntax for initializing normal properties.

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

exactly the same as

 var person = new Person(); person.FirstName = "Bob"; person.LastName = "smith"; 

And as people said. Your example will not compile. Because its not a constructor.

+4
source

How can you compile this? C # reports an error:

 error CS0106: The modifier 'readonly' is not valid for this item 
+1
source

I assume that you mean private poppy installers instead of readonly properties (get and set are short for full getters and seters). Then you will need to do something like this to reflect the properties:

 Type personType= typeof(Person); object personInstance = Activator.CreateInstance(personType); personInstance.GetProperty("FirstName").SetValue(classObject, "Bob, null); personInstance.GetProperty("LastName").SetValue(classObject, "smith, null); 
0
source

Source: https://habr.com/ru/post/1341691/


All Articles