Skip to main content
 首页 » 编程设计

c#之如何在 C# Windows 应用程序中将字符串值保存到另一个字符串

2024年02月13日29tintown

我在 class Form1 : Form 中定义了一个用户名

而 user_name 在上面定义为,

string user_name = "Rammy"; 

我想在下面的行中使用这个user_name,但它没有执行,并给出错误“A field initializer cannot reference the non-static field, method, or property”。

string copyright_bottom_text = user_name; 

有人可以帮忙吗?我正在使用 visual studio 2012。

请您参考如下方法:

将下行移动到构造函数或方法

string copyright_bottom_text = user_name; 

Compiler Error CS0236

Instance fields cannot be used to initialize other instance fields outside a method. If you are trying to initialize a variable outside a method, consider performing the initialization inside the class constructor. For more information, see Methods (C# Programming Guide).

public class MyClass 
{ 
   public int i = 5; 
   public int j = i;  // CS0236 
   public int k;      // initialize in constructor 
 
   MyClass() 
   { 
      k = i; 
   } 
 
   public static void Main() 
   { 
   } 
}