我一直在乱用C#,我偶然发现了一个我无法找到答案的问题。我在另一个.cs文件的main中创建了两个对象,我想为另一个类中与该对象关联的变量赋值。经过大约一个小时的观察,我不知道该怎么做。这是我的代码(我知道它不完美;我刚开始学习):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Converse
{
class Program
{
static void Main(string[] args)
{
Subject subject1 = new Subject();
Subject subject2 = new Subject();
Generate.generation();
}
}
}
然后
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Converse
{
public class Subject
{
public int persuasion;
public Subject()
{
persuasion = 0;
}
}
}
在最后一个问题上,第17和第19行是问题所在:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Converse
{
public static class Generate
{
public static void generation()
{
Console.WriteLine("Control over Subject 1's personality? ");
Console.WriteLine("1) None");
Console.WriteLine("2) Minimal");
Console.WriteLine("3) Considerable");
subject1.persuasion = Console.ReadKey();
switch (subject1.persuasion)
{
case 1:
break;
case 2:
GenerationFunctions.lightGen();
break;
case 3:
GenerationFunctions.heavyGen();
break;
default:
break;
}
Console.ReadKey();
}
}
}
有人可以告诉我如何正确编码吗?
由于
答案 0 :(得分:1)
您的代码存在多个问题。您需要将对主题的引用传递给generation void。
public static void generation(Subject subject)
{
Console.WriteLine("Control over Subject 1's personality? ");
Console.WriteLine("1) None");
Console.WriteLine("2) Minimal");
Console.WriteLine("3) Considerable");
subject.persuasion = Convert.ToInt32(Console.ReadKey());
switch (subject.persuasion)
{
case 1:
break;
case 2:
GenerationFunctions.lightGen();
break;
case 3:
GenerationFunctions.heavyGen();
break;
default:
break;
}
}
然后致电:
Subject subject1 = new Subject();
Generate.generation(subject1);