我试图在一个类中使用在另一个类中创建的对象。反正有这样做吗?我正在向您显示代码:
在名为Item的此类中,我最后创建了一个名为spellwand的对象。
namespace RPG.Entities
{
public class Item
{
public string Name { get; set; }
public int Damage { get; set; }
public int MagicalDamage { get; set; }
public int Defense { get; set; }
public int Resistance { get; set; }
public Item(string name, int damage, int magicalDamage, int defense, int resistance)
{
Name = name;
Damage = damage;
MagicalDamage = magicalDamage;
Defense = defense;
Resistance = resistance;
}
Item spellwand = new Item("Spellwand", 0, 12, 0, 0);
}
现在,在这个角色类中,我创建了下一个方法:
using RPG.Entities;
using System.Collections.Generic;
using System;
namespace RPG.Entities
{
public class Character
{
public List<Item> Item { get; set; }
public void AddItem(Item item)
{
Item.Add(item);
}
}
}
很酷,现在在Battle类中,我想称呼为Item类创建的对象“ spellwand”。
namespace RPG.Entities
{
public class Story
{
public void Battle()
{
Character eskilie = new Character("Eskilie", "Magician");
eskilie.AddItem(spellwand);
}
}
}
反正有这样做吗?
顺便说一句,在Battle中出现的错误是“该对象咒语在当前上下文中不存在”。
答案 0 :(得分:1)
我认为您需要做的是在Story中将项目创建为这样的列表:
// Create a big array containing items with names generated randomly for testing purposes
let jsonData = [];
for (i = 0; i < 10000; i++) {
var itemName = '';
jsonData.push({ item: Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) });
}
// Now on to the actual search part
let returnLimit = 1000; // Maximum number of results to return
let intervalItr = null; // A handle used for iterating through the array with an interval timer
function nameInput (e) {
document.getElementById('output').innerHTML = '';
if (intervalItr) clearInterval(intervalItr); // If we were iterating through a previous search, stop it.
if (e.value.length > 0) search(e.value);
}
let reg, idx
function search (enteredName) {
reg = new RegExp(enteredName, 'i');
idx = 0;
// Kick off the search by creating an interval that'll call searchNext() with a 0ms delay.
// This will prevent the search function from locking the main thread while it's working,
// allowing the DOM to be updated as you type
intervalItr = setInterval(searchNext, 0);
}
function searchNext() {
if (idx >= jsonData.length || idx > returnLimit) {
clearInterval(intervalItr);
return;
}
let item = jsonData[idx].item;
if (reg.test(item)) document.getElementById('output').innerHTML += '<br>' + item;
idx++;
}
然后从Item类中删除新项目
namespace RPG.Entities
{
public class Story
{
// Store all your possible game items here
protected List<Item> GameItems = new List<Item>();
public Story()
{
// Add your game items
GameItems.Add(new Item("Spellwand", 0, 12, 0, 0));
GameItems.Add(new Item("Axe", 0, 14, 0, 0));
}
public void Battle()
{
Character eskilie = new Character("Eskilie", "Magician");
// Add item
var spellwand = GameItems.Where(i => i.name == "Spellwand").FirstOrDefault();
eskilie.AddItem(spellwand)
}
}
}
理想情况下,您将拥有一个ItemRepository类,该类将检索所有游戏项目,但希望这可以使您对开始的结构有所了解。