我正在爲我的Unity遊戲製作一個物品系統,並且正在使用C#來完成它。我有一個名爲ItemType的抽象類,它包含有關特定類型項目(如名稱,權重,市場價值,ID等)的信息。然後我必須從ItemType類繼承的Item Item,ItemSword和ItemCoin。我也有一個ItemManager類,它實例化ItemCoin和ItemSword,併爲我自動分配一個ID。我的問題是當我嘗試繼承類時,我遇到了構造函數的錯誤。對C#和構造函數有問題。「ItemType.ItemType(字符串)由於其保護級別而無法訪問」
ItemType的構造函數接受一個參數,一個名爲name的字符串。當我去到做ItemCoin構造函數中,我要確保它要求使用
ItemCoin(string name): base(name){
//Stuff
}
就像它說this page的基類。
錯誤是說「名稱」由於其保護級別而無法訪問,就好像我已將其設爲私有。雖然我不明白這是可能的,因爲我沒有給任何種訪問修飾符,因爲它是一個參數。 ItemSword不會給我這個錯誤,但這很可能是因爲編譯器仍然卡在ItemCoin上。
當我沒有給「base」任何參數時,它告訴我ItemType沒有帶0參數的構造函數。如果我根本不使用「base」,或者如果我不給它任何構造函數,同樣的事情會發生。
僅供參考,這裏是我的完整源代碼。
ItemType.cs:
using UnityEngine;
using System.Collections;
public abstract class ItemType{
public int itemID; //The id of this item
public string itemName; //The text name of this item
public int stackSize = 99; //The maximum amount of this item allowed in a stack. Use -1 for infinite
public int maxAllowedInOneContainer = -1; //The maximum amount of this item allowed in a single container. Use -1 for infinite.
public int weight = 0; //The weight of this item
public int marketValue = 0; //The standard price of this item in stores
ItemType(string name){
itemName = name;
}
}
ItemCoin.cs:
using UnityEngine;
using System.Collections;
public class ItemCoin : ItemType {
ItemCoin(string name): base(name){
stackSize = -1;
}
}
ItemSword.cs:
using UnityEngine;
using System.Collections;
public class ItemSword : ItemType{
ItemSword(string name): base(name){
maxAllowedInOneContainer = 1;
stackSize = 1;
}
}
ItemManager.cs:
using UnityEngine;
using System.Collections;
public class ItemManager {
public const int MAX_ITEMS = 3200;
private static ItemType[] itemList = new ItemType[MAX_ITEMS];
public static int numberOfItems = 0;
ItemManager(){
/*When you make a new item, add it to this huge list of item declarations, or else it won't do anything!*/
ItemSword sword = addItem(new ItemSword("Sword")); //Adds the sword item
ItemCoin coin = addItem(new ItemCoin("Coin"));
}
public ItemType addItem(ItemType item){
//Add the item to the list
itemList[numberOfItems] = item;
//Tell the item its id number
item.itemID = numberOfItems;
//Increment the total number of items by one. This will be the id of the next added item.
numberOfItems += 1;
return item;
}
public int findItemID(string name){
//Finds the item id for an item with a given name
bool found = false;
for (int i = 0; i < numberOfItems; i++){
if (itemList[i].itemName == name){
found = true;
return itemList[i].itemID;
break;
}
}
if (found == false){
throw new ItemIDNotFoundException();
}
}
public string findItemName(int id){
if (id >= itemList.Length){
throw new ItemIDNotFoundException();
}
else{
return itemList[id].name;
}
}
public ItemType GetItem(int id){
//Returns a reference(pointer) to the item type with a given id.
return itemList[id];
}
}
同意。在'abstract'類中,擁有'public'(或'protected internal')實例構造函數是沒有意義的。但如果他願意,他可以把它變成「內部」。但是,對於抽象類的實例構造函數,「protected」是最自然的(也是限制最少的)訪問級別。 – 2013-02-23 21:51:49