Referring to C # dynamic members 'dynamic' object

I am using JSON.NET to deserialize a JSON file for a dynamic object in C #.

Inside the method, I would like to pass a string and refer to the specified attribute in a dynamic object.

For instance:

 public void Update(string Key, string Value) { File.Key = Value; } 

Where File is a dynamic object, and Key is the string to which it is passed. Say I would like to pass the key "foo" and the value "bar", I would do: Update("foo", "bar"); , however, due to the nature of the dynamic object type, this leads to

 { "Key":"bar" } 

Unlike:

 { "foo":"bar" } 

Is it possible to do what I ask here with a dynamic object?

+5
source share
3 answers

I suspect you could use:

 public void Update(string key, string Value) { File[key] = Value; } 

It depends on how the dynamic object implements indexing, but if it is Json.NET JObject or similar, I expect it to work. It is important to understand that this did not guarantee performance for general dynamic expressions, though.

If you really need this operation (at least inside the class), you can use JObject as a field type and then just expose it as dynamic when you need to.

+4
source

Well, it so happened that I am special. Here's the answer for those who might stumble upon this in the future,

Turns out you can just use the key as an array index, and it works great. So:

File[Key] = Value; It works as I need, unlike File.Key = Value;

Thank you anyway!

+2
source

You can do this if using JObject from JSON.NET. It does not work with ExpandoObject .

Example:

 void Main() { var j = new Newtonsoft.Json.Linq.JObject(); var key = "myKey"; var value = "Hello World!"; j[key] = value; Console.WriteLine(j["myKey"]); } 

This simple example prints "Hello World!" as expected. Hence

 var File = new Newtonsoft.Json.Linq.JObject(); public void Update(string key, string Value) { File[key] = Value; } 

does what you expect. If you declare File in the above example as

 dynamic File = new ExpandoObject(); 

you will get a runtime error:

CS0021 Cannot apply indexing with [] to an expression of type "ExpandoObject"

+1
source

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


All Articles