基本上我是在C#中制作一个刽子手游戏,但问题是每当我尝试将string
字转换为char[]
并word.ToCharArray();
时,它都无效。
有人能弄清楚这段代码有什么问题吗?
List<string> words = new List<string>();
List<string> guessedLetters = new List<string>();
string word = "sword";
// Turning word into char array
char[] letters = word.ToCharArray();
CS0236字段初始值设定项不能引用非静态字段,方法或属性&#39; Form1.word&#39; final C:\ Users * \ Desktop \ final \ final \ Form1.cs 20 Active
答案 0 :(得分:1)
到目前为止,已知的是一个名为Form1
的类:
public class Form1 {
List<string> words = new List<string>();
List<string> guessedLetters = new List<string>();
string word = "sword";
//...
public static void Main(string[]args){
char[] letters = word.ToCharArray();
}
}
如果是这种情况那么,你做错了。您需要类Form1
的对象才能使用变量word
。
public static void Main(string[]args){
Form1 F1 = new Form1();
char[] letters = F1.word.ToCharArray();
}
答案 1 :(得分:0)
我怀疑你有类似的东西可以使用static
修复
但这可能不是最好的设计。
class Program
{
List<string> words = new List<string>();
List<string> guessedLetters = new List<string>();
static string word = "sword";
char[] letters = word.ToCharArray();
这可能是更好的设计:
public List<string> words { get; } = new List<string>();
public List<string> guessedLetters { get; } = new List<string>();
public string word { get; set; } = "sword";
public char[] letters { get { return word.ToCharArray(); } }
答案 2 :(得分:0)
错误表示在调用的静态方法下需要静态字段,因此将单词更改为静态 -
static string word = "sword";
答案 3 :(得分:0)
从技术上讲,您可以将初始化移动到构造函数:
public partial class Form1: Form {
...
List<string> words = new List<string>();
List<string> guessedLetters = new List<string>();
string word;
// Turning word into char array
char[] letters;
public Form1() {
word = "sword";
letters = word.ToCharArray();
}
}
另一种可能性是声明属性:只要你想将word
分成字母,只需调用letters
属性
public partial class Form1: Form {
...
List<string> words = new List<string>();
List<string> guessedLetters = new List<string>();
string word = "sword";
...
private char[] letters {
get {
return null == word
? new char[0]
: word.ToCharArray();
}
}
答案 4 :(得分:0)
来自Microsoft Docs: "Instance fields cannot be used to initialize other instance fields outside a method."
它是一个编译器决定,就是这样。或者用变量设定一个常数,像这样的小东西就是设计决定,而且它们背后的季节大小都像品味一样。
您可以通过word
static
来修复它,但我不知道这是否是您想要的。