简体   繁体   中英

How can I make a list of a certain class, but still allow extensions of the class to be allowed in the list with all of their parameters C#

So I am writing an item system for unity C#, and I have this base item class that I extend upon for different types of items, for example I would extend the base class and add a variable for attack and attack speed, and a function for attacking for a weapon class.

But my issue is I am writing a database for the items, and I want to store these different classes into one big list, but when I make a list of Base Items, and I pass a weapon item, it cleaves away the attack function and the attack variables, and basically turns the weapon item into a base item, rendering it useless.

如果您喜欢RDBMS,而不是像SledgeHammer建议的那样使用NOSQL,那么您可能会在这里找到答案。

There are two main ways of doing this in a relational database, which is what most common database systems are.

  1. You can have different tables for each type of Item, so Weapon s have one table, Potion s have another, and the Item table is a list of (Name, Type, Id) tuples, telling you which item in which table to look at to get its exact details. This will require one table for each class of item, but if you are careful, you only need a few.

  2. Have an Item table, which stores an Item Type (again). You also have an "Attribute" table, which has columns ItemId, Attribute, Value So if you have a sword with speed 5 and damage 10, and a potion that heals 3, you would have the following rows

     Item ==== Id | Name | Category 1 | "Sword" | "weapon" 2 | "Healing Potion" | "potion" Attribute ========= ItemId | Attribute | Value 1 | "speed" | 5 1 | "damage" | 10 2 | "healing" | 3 

It's then up to you to join on ItemId, and pivot the rows into columns and convert into your item's class.

Or you can use a document-based database, as the other answers suggest.

Sounds like you want to use a document store instead of a RDBS. RDBS requires all items in a table to be of the same type. The drawback is you end up with a bunch of NULL columns for the types that don't contain all the columns which makes everything hokey. A document store is schema-less, so you only have the attributes that pertain to the type.

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