C# code error: "An object reference is required to access a non-static field, method, or property"
The provided code snippet throws an error in Class 2 (Implementing Algorithm) due to an attempt to access a non-static method Main()
from a static method GetRandomBits()
.
In the Main()
method, the line Population[i].bits = GetRandomBits();
caused the error. The problem is that GetRandomBits()
is a non-static method in the Program
class, while Main()
is a static method.
Solution: static vs. non-static
Solution:
Program
class and call GetRandomBits()
from that instance. <code class="language-csharp">// 创建 Program 实例 Program p = new Program(); // 从实例访问非静态方法 Population[i].bits = p.GetRandomBits();</code>
GetRandomBits()
static: Modify the static
method to a static method by adding the GetRandomBits()
keyword before the method declaration. <code class="language-csharp">public static string GetRandomBits() { // 在此处实现方法逻辑... }</code>
Which method you choose depends on your program design and the purpose of the GetRandomBits()
method. If GetRandomBits()
needs to access other non-static members of the class, it must use the first method (create instance). If GetRandomBits()
doesn't need to access non-static members of the class, the second approach (making it static) is cleaner. Remember, overuse of static methods may make your code less testable and maintainable.
The above is the detailed content of Why Does 'An Object Reference is Required' Appear When Calling a Non-Static Method from a Static Method in C#?. For more information, please follow other related articles on the PHP Chinese website!