C# 在c中使用另一个类函数#
我正在尝试从dieclass调用函数,并在matchplay类中使用卷号。。。这可能吗C# 在c中使用另一个类函数#,c#,function,methods,dice,C#,Function,Methods,Dice,我正在尝试从dieclass调用函数,并在matchplay类中使用卷号。。。这可能吗 public class DieClass { public void DiceRoll(int min, int max) { Random random = new Random(); int roll1 = random.Next(0, 6); int roll2 = random.Next(0, 6); int roll
public class DieClass
{
public void DiceRoll(int min, int max)
{
Random random = new Random();
int roll1 = random.Next(0, 6);
int roll2 = random.Next(0, 6);
int roll3 = random.Next(0, 6);
}
}
public class MatchPlay
{
public void Match()
{
DieClass.DiceRoll();
Console.WriteLine("Starting Match Play...");
Console.WriteLine();
Console.WriteLine("Round One");
Console.WriteLine("Your first dice is [0]", roll1);
Console.WriteLine("Your second dice is [0]", roll2);
Console.WriteLine("Your third dice is [0]", roll3);
}
}
}您需要创建
dicerll
一个static
方法,或者创建DieClass
的实例并通过该实例调用您的方法
例如,您可以将您的方法声明为
public static void DiceRoll(int min, int max)
或者您可以实例化一个对象,如:
DieClass dice = new DieClass();
dice.DiceRoll(0, 6);
也就是说,您的
DieClass
类还有其他问题,最明显的问题是您需要一种将结果反馈给调用者的方法。最简单的方法是让DiceRoll()
生成一个结果并返回该结果。此外,您已经将0
和6
硬编码为random.Next()
的参数,尽管该方法需要一对参数min
和max
有几件事需要解决:
- 您的
方法是一个实例方法,因此您需要创建DiceRoll
类的实例才能使用它李>DiceClass
、roll1
和roll2
变量是该方法的局部变量,因此一旦该方法完成,您将无法使用它们。相反,您可以使它们成为类的公共属性李>roll3
- 您不需要每次调用该方法时都实例化一个新的
(事实上,这可能会导致问题,因为Random
的种子值基于系统时钟,因此,如果您的方法调用得非常快,它将反复生成相同的数字)。您可以将其设置为静态并实例化一次李>Random
- 既然您在
方法中引入了Roll
和min
参数,我们不应该使用它们吗?您当前有max
和0
硬编码李>6
- 要使用格式字符串,需要使用大括号(
)而不是方括号({}
)[]
- 最后,从命名约定的角度来看,不需要将单词
作为类名的一部分,也不需要将Class
作为方法名的一部分。这将简化键入的数量,并且仍然非常容易理解Dice
您可以考虑创建一个类,该类表示单个<代码>模具>代码>对象,并给它一个<代码>滚动()/<代码>方法和一个<代码>值属性。然后,用户可以创建任意数量的文件,并将其保存在列表中:
public class Die
{
public int Value { get; set; }
// Make this static and instantiate it only once to avoid re-seeding issues
private static readonly Random rnd = new Random();
public Die()
{
Value = 1;
}
public void Roll()
{
// This method uses values 1-6 as a standard die
Roll(1, 6);
}
public void Roll(int minValue, int maxValue)
{
Value = rnd.Next(minValue, maxValue + 1);
}
}
现在,您可以使用Die
类,如下所示:
public class MatchPlay
{
public void Match()
{
// Add three Die objects to our list of dice
List<Die> dice = new List<Die>
{
new Die(), new Die(), new Die()
};
Console.WriteLine("Starting Match Play...");
Console.WriteLine();
Console.WriteLine("Round One");
// Roll all dice
dice.ForEach(d => d.Roll());
Console.WriteLine("Your first dice is {0}", dice[0].Value);
Console.WriteLine("Your second dice is {0}", dice[1].Value);
Console.WriteLine("Your third dice is {0}", dice[2].Value);
}
}
类不是对象,更像是蓝图。您需要实例化和类型为DieClass的对象,才能将其用作对象。你还需要先阅读和学习C#basics。要么创建静态方法,要么实例化DieClass。同时传递最小、最大参数。您需要返回值才能打印它们。干得好。我也会让Roll返回值,但这是一个小点哦,这是个好主意。然后您可以同时
滚动
并输出值
Console.WriteLine(“滚动骰子后,值为:{0}”,骰子[0].Roll())代码>
private static void Main()
{
MatchPlay game = new MatchPlay();
game.Match();
Console.WriteLine("\nDone!\nPress any key to exit...");
Console.ReadKey();
}