C# error: "A reference to an object is required to use non-static fields"
This C# code contains two classes: one defines the algorithm parameters and the other implements the algorithm. In the Main
method of the second class, I get the following error:
<code>需要对象的引用才能使用非静态字段、方法或属性 'VM_Placement.Program.GetRandomBits()'</code>
This error is because the Main
method is static and you are trying to call a non-static method in GetRandomBits()
.
Solution:
To solve this problem, you can choose the following two methods:
Create an instance of the Program class:
In the Main
method, create an instance of the Program
class and then call GetRandomBits()
on that instance:
<code class="language-csharp">Program p = new Program(); string bits = p.GetRandomBits();</code>
Make the GetRandomBits() method static:
Modify the GetRandomBits()
method declaration to make it a static method:
<code class="language-csharp">public static string GetRandomBits() { ... }</code>
After making a method static, you can call it directly without creating an instance of the Program
class.
The above is the detailed content of Why Does 'An Object Reference is Required for the Non-Static Field' Occur in C# and How Can It Be Fixed?. For more information, please follow other related articles on the PHP Chinese website!