Значение ссылочной переменной зануляется
Мне необходимо использовать переменные из класса Input в классе алгоритм, но при обращении к ним, они равны нулю. Подскажите, пожалуйста, что я делаю не так
using System;
using System.IO;
namespace ОСАПР
{
class Program
{
public static void Main(string[] args)
{
var inp = new Input();
inp.INPUT();
Console.WriteLine("n из мейна " + inp.n);
Console.WriteLine("m из мейна " + inp.m);
Algorithm Al = new Algorithm();
Al.ALG();
Console.ReadKey();
}
class Input
{
public int alpha { get; set; }
public int beta { get; set; }
public int n { get; set; }
public int m { get; set; }
public int[,] Matrix { get; set; }
public void INPUT()
{
StreamReader f = new StreamReader(@" C:\Users\IIsha\source\repos\ОСАПР\Данные.txt");
alpha = Convert.ToInt32(f.ReadLine());
beta = Convert.ToInt32(f.ReadLine());
n = Convert.ToInt32(f.ReadLine());//строки
m = Convert.ToInt32(f.ReadLine());//столбики
string[] array = new string[n];//записываем строки из txt
int[] arr = new int[n];//записываем числа
Matrix = new int[n, m];
while (!f.EndOfStream)
{
string ss = f.ReadLine();
array = ss.Split(new char[] { ' ' });
for (int i = 0; i < n; i++)
{
int.TryParse(array[i], out arr[i]);
}
Matrix[arr[0] - 1, arr[1] - n - 1] = arr[2];
}
Console.WriteLine("Матрица расстояний:");
for (int i = 0; i < n; i++)//матрица
{
for (int j = 0; j < m; j++)
{
Console.Write(Matrix[i, j]);
Console.Write(" ");
}
Console.WriteLine();
}
f.Close();
Console.WriteLine("n из инпута " + n);
}
}
class Graph
{
}
class Algorithm
{
public int[,] Distances { get; set; }//матрица вероятностей перехода
public int[,] Verification_matrix { get; set; }//матрица проверки были ли выбрана вершина ранее
public double dist { get; set; }//расстояние между вершинами
public void ALG()
{
var INP = new Input();
Console.WriteLine("n из аглоритма " + INP.n);
Console.WriteLine("m из аглоритма " + INP.m);
Distances =new int[INP.n, INP.m];
Verification_matrix = new int[INP.n, INP.m];
int prob_str=0;//сумма вероятностей строки
for (int i = 0; i < INP.n; i++)
{
Console.WriteLine("хочу увидеть это сообщение!!1");
for (int j = 0; j < INP.m; j++)
{
prob_str = prob_str + 1/ INP.Matrix[i, j];
Console.WriteLine(prob_str = prob_str + 1 / INP.Matrix[i, j]);
}
for (int j = 0; j < INP.m; j++)
{
//dist = (1 / INP.Matrix[i, j])^INP.beta/();
}
prob_str = 0;
}
}
}
}
}
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
В мейне вы после создания класса вызываете метод, загружающий данные
var inp = new Input();
inp.INPUT();
А в алгоритме не вызываете
var INP = new Input();
new создает новый экземпляр класса, его пустую копию. Это ООП.
Решить можно двумя способами:
- Вызвать
inp.INPUT();в алгоритме - Передать уже созданный
Inputв алгоритм (на мой взгляд более правильно)
Можно передать в метод:
public void ALG(Input input)
{
Console.WriteLine("n из аглоритма " + input.n);
Console.WriteLine("m из аглоритма " + input.m);
// остальной код...
}
И вызвать так
Algorithm Al = new Algorithm();
Al.ALG(inp);
Можно передать в конструктор:
private Input input;
public Algorithm(Input inp)
{
input = inp;
}
public void ALG()
{
Console.WriteLine("n из аглоритма " + input.n);
Console.WriteLine("m из аглоритма " + input.m);
// остальной код...
}
И вызывать вот так
Algorithm Al = new Algorithm(inp);
Al.ALG();
Совет, не делайте вложенных типов. У вас такая структура
class
{
class { }
class { }
}
А надо вот так
class { }
class { }
class { }
Меньше путаться будете