简体   繁体   中英

Create an class or an object that can have different properties everytime in C#

I have a class which has a property named properties but that property can have different values. Those are dynamic values coming from somewhere and I need to create a request with a structure of Json which has Customer and properties can have different values. I tried the following:

Customer Class

public class Customer{
  public string name {get;set;}
  public dynamic properties {get;set;}
}

These properties can be dynamic. For example - This can be the json that I get

1st Example:

"properties":{
  "name": "Mark",
  "address": {
    "city":"paris"
   }
}

2nd Example:

"properties":{
  "name": "Chris",
  "description":"human",
  "birth":"1990",
  "address": {
    "name":"paris"
   }
}

Whenever I do properties.address.name, it says it can refer to the null reference. I am not sure if dynamic type is correct. How this should be done in C#. If the property can have different values, what is the approach you take?

Dynamic types are complex but in short, they are evaluated in run time instead of compile time (see: https://www.geeksforgeeks.org/dynamic-type-in-c-sharp/ ). It doesnt seem like this is what you are dealing with and you can simplify the solution.

It looks like there are many answers to your question (short google came up with: Add properties dynamically at run time in existing class c# and many more) which you can try and implement.

However - maybe it would be easier to use json supporting packages like newtonsoft.json and have a json object as Properties .

Then you would be able to both add and use the json elements (properties):

using Newtonsoft.Json;

public class Customer 
{   
   public string Name {get;set;}   
   public JObject Properties {get;set;} = new JObject();
}

Add with:

customer.Properties["evilProp"] = 666;

And get it with:

var numberFromHell = customer.Properties["evilProp"];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM