简体   繁体   English

C# Object 未设置键值类型

[英]C# Object with unset key value types

My goal: I want to create a system that can have key value pairs but that I don't need to beforehand set either the key or the value's data type我的目标:我想创建一个可以有键值对但我不需要事先设置键或值的数据类型的系统

What I am trying to emulate to an extent is pythons dictionaries我试图在一定程度上模仿的是 pythons 字典

example of what I want我想要的例子

{
  "hotbar"=
  {
             {"slot_1"={"item"="dirt","amount"=3},
             {"slot_3"={"item"="shovel","amount"=1,"usesLeft"=135}
  }
  "walkspeed"=10
  "jumpPower"=15
  "position"={"x"=10,"y"=3,"z"=31.3}

similar to Minecraft's nbt system is my goal类似于 Minecraft 的 nbt 系统是我的目标

the syntax does not need to be perfectly the same just as long as I can store it with a key and value without it mattering what type of key and value it is语法不需要完全相同,只要我可以用键和值存储它,而不管它是什么类型的键和值

And I want to be able to read and write individual values from this (including nested values) and also to loop through all of the key value pairs as well我希望能够从中读取和写入单个值(包括嵌套值),并且还希望能够遍历所有键值对

please recomend me better tags请推荐我更好的标签

Key value things is Dictionary https://www.tutorialsteacher.com/csharp/csharp-dictionary but in OOP you can just use List of objects关键值是 Dictionary https://www.tutorialsteacher.com/csharp/csharp-dictionary但在 OOP 中,您可以只使用对象列表
eg //Design Objects (classes) eg //设计对象(类)

public class Hotbar { //Hotbar class
   public string key_name {get;set;}
   public stirng item {get;set;}
   public int amount{get;set;}   
   public int usesLeft{get;set;}
}

public class YourMainClass{
  public List<Hotbar> hotbar_List {get;set;}
  public int walkspeed {get;set;}
  public int jumpPower {get;set;}
  public PositionObj position {get;set;} // go create object of position
  public YourMainClass(){
   // constructor  Init List 
   hotbar_List   =new List<hotbar>();
  }

}

example how to use示例如何使用

YourMainClass targetObj =new YourMainClass();
// create new Hotbar
  Hotbar  hotbar1  =new Hotbar();
  hotbar1.key_name  = "slot_1";
  hotbar1.item  ="dirt";
  hotbar1.amount= 3;
// add  hotbar #1
 targetObj.hotbar_List.Add(hotbar1);

// get hot bar slot_1
 Hotbar thatHot = targetObj.hotbar_List.Where(o=>o.key_name  =="slot_1").FirstOrDefault();

// for looping - will loop if there are obj in List
 foreach( Hotbar  oneHotBar from  targetObj.hotbar_List  ){
  // do something with hotbar   Obj call oneHotBar 
   string name_of_item = oneHotBar.key_name  ; 
  // try minus amount 
   if( oneHotBar .key_name  =="slot_1" )
   {
      oneHotBar. amount =  oneHotBar. amount-1;
   }
 }

ps sorry I'm not fluent with Dictionary please wait for others. ps对不起,我不流利的字典请等待其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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