Почему не создается экземпляр моего объекта graph
Я не могу показаться, чтобы получить мой график должен быть инициализирован в классе GraphComponents в методе Main. Я постоянно получаю ошибку "ССЫЛКА на объект не установлена на экземпляр объекта", независимо от того, какой подход я использую.
Я использую repl.it чтобы попытаться заставить эту программу работать.
using System; using System.Collections.Generic; public class MainClass { public static void Main (string[] args) { Console.WriteLine("Connected Graph Components"); GraphComponents gC = new GraphComponents(); Graph graph = gC.GetGraph(); int size = graph.Size; for (int v = 0; v < size; ++v) { if (!gC.visited[v]) { gC.TraverseDFS(v); Console.WriteLine(); } } } } public class Graph { public List<int>[] childNodes; public Graph(int size) { this.childNodes = new List<int>[size]; for (int i = 0; i < size; ++i) { this.childNodes[i] = new List<int>(); } } public Graph(List<int>[] childNodes) { this.childNodes = childNodes; } public int Size { get { return this.childNodes.Length; } } public void AddEdge(int u, int v) { childNodes[u].Add(v); } public void RemoveEdge(int u, int v) { childNodes[u].Remove(v); } public bool HasEdge(int u, int v) { bool hasEdge = childNodes[u].Contains(v); return hasEdge; } public IList<int> GetSuccessors(int v) { return childNodes[v]; } } public class GraphComponents { public static Graph graph; public GraphComponents() { graph = new Graph(new List<int>[] { new List<int>() {4}, // successors of vertice 0 new List<int>() {1, 2, 6}, // successors of vertice 1 new List<int>() {1, 6}, // successors of vertice 2 new List<int>() {6}, // successors of vertice 3 new List<int>() {0}, // successors of vertice 4 new List<int>() {}, // successors of vertice 5 new List<int>() {1, 2, 3} // successors of vertice 6 }); } public bool[] visited = new bool[graph.Size]; public void TraverseDFS(int v) { if (!visited[v]) { Console.WriteLine(v + " "); visited[v] = true; foreach (int child in graph.GetSuccessors(v)) { TraverseDFS(child); } } } public Graph GetGraph() { return graph; } }
Что я уже пробовал:
Я попытался получить доступ к инициализированному графу непосредственно с помощью объекта GraphComponents, а также создал метод для возврата графа мне, но он, похоже, не инициализирует граф в конструкторе GraphComponents.
В конечном итоге вы получили ошибки от различных попыток:
1. инициализатор поля не может ссылаться на нестатическое поле, метод или свойство
2. статический член `GraphComponents.graph' не может быть доступен со ссылкой на экземпляр, вместо этого квалифицируйте его именем типа
3. инициализатор поля не может ссылаться на нестатическое поле, метод или свойство GraphComponents.graph