[英]C# How can I change the value from static class?
所以這是程序cs。 我想在我的 StaticClass.cs 中更改 int 的值 ** 我想打印一個打印句“你希望我生成多長時間”然后更改 StaticClass 中 N 的值。
class Program
{
static void Main(string[] args)
{
Constructor ct = new Constructor(StaticClass.n);
//ct.xmethod(StaticClass.n);
Console.ReadKey();
}
}
這是我的構造函數類。 帕斯卡三角法
class Constructor
{
int[][] triangle = new int[StaticClass.n][];
public Constructor(int n)
{
xmethod(n);
}
public void xmethod(int n)
{
for (int row = 0; row < triangle.Length; row++)
{
//Each row is a subarray of length 1 greater than row number
triangle[row] = new int[row + 1];
//set the values in a row
for (int k = 0; k < triangle[row].Length; k++)
{
// if not first or last element in the row
if (k > 0 & k < triangle[row].Length - 1)
//set it to sum of the element above it
//and the one above and to the left
triangle[row][k] = triangle[row - 1][k - 1] + triangle[row - 1][k];
//otherwise this is an end point, set it to 1
else
triangle[row][k] = 1;
//display value
Console.Write(triangle[row][k] + "\t");
}
// Finished processing row-send cursor to next line
Console.WriteLine();
}
}
}
這里我的靜態類很長帕斯卡三角形
class StaticClass
{
public const int n = 15;
// I want to change the value of N using the Console Writeline.
}
您不能更改 const 的值。 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants
請改用靜態屬性。
static class StaticClass
{
public static int n = 15;
// I want to change the value of N using the Console Writeline.
}
n
需要是可更新的,然后使用static
代替const
; 但是Console.WriteLine()
不是您用來更改值的東西。 你需要更清楚你想要做什么。 您是否希望有人使用 Console.ReadLine 輸入n
的值?
所以......從我收集的信息來看——我認為你想改變你的Main
來寫你的問題:“你希望我生成多長時間”然后閱讀用戶輸入的行。 然后打印你的三角形。 就像是 :
static void Main(string[] args)
{
Console.WriteLine("How long do you want me to generate? ");
int inNum = int.Parse(Console.ReadLine());
Constructor ct = new Constructor(inNum);
Console.ReadKey();
}
然后從我所看到的......你的Constructor
需要改變:
public Constructor(int n)
{
triangle = new int[n][];
xmethod(n);
}
將您的公共 const 字段改為公共靜態屬性:
public static int N { get; set; } = 15;
改成這樣
StaticClass.N = 16;
你說“用 WriteLine 改變它” - WriteLine 輸出東西,它不會改變東西。 也許你的意思是 ReadLine:
Console.WriteLine("How many levels? ");
string input = Console.ReadLine();
StaticClass.N = int.Parse(input);
請為 StaticClass 找一個更好的名字; 類應該根據它們在更真實世界的意義上代表的東西(比如..配置?)而不是它們在 C# 意義上的名稱(是的,它是一個靜態類,但這並不意味着我們應該這樣稱呼它)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.