簡體   English   中英

在 C# 中創建每次都可以具有不同屬性的類或對象

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

我有一個類,它有一個名為 properties 的屬性,但該屬性可以有不同的值。 這些是來自某處的動態值,我需要創建一個具有 Json 結構的請求,該結構具有 Customer,屬性可以具有不同的值。 我嘗試了以下方法:

客戶類別

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

這些屬性可以是動態的。 例如 - 這可以是我得到的 json

第一個例子:

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

第二個例子:

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

每當我執行 properties.address.name 時,它​​都會說它可以引用空引用。 我不確定動態類型是否正確。 這應該如何在 C# 中完成。 如果財產可以有不同的價值,你采取什么方法?

動態類型很復雜,但簡而言之,它們在運行時而不是編譯時進行評估(請參閱: https : //www.geeksforgeeks.org/dynamic-type-in​​-c-sharp/ )。 這似乎不是您正在處理的問題,您可以簡化解決方案。

看起來您的問題有很多答案(簡短的 google 提出: 在現有類 c# 中在運行時動態添加屬性等等),您可以嘗試並實現它們。

但是 - 也許使用像newtonsoft.json這樣的 json 支持包並有一個 json 對象作為Properties會更容易。

然后你就可以添加和使用 json 元素(屬性):

using Newtonsoft.Json;

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

添加:

customer.Properties["evilProp"] = 666;

並通過以下方式獲取:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM