我對C#
非常陌生,我無法想象從另一個文件到達變量,表單屬性和駐留在一個文件中的其他方法。我覺得,這應該像#include
指令那樣簡單,但是找不到方法。爲什麼我無法從其他文件訪問表單屬性?
這是我在VS中創建一個新的Windows窗體應用程序時創建的文件Form1.cs
中的代碼。我可以訪問位於另一個名爲Class1.cs
的文件中的類定義;這裏沒有問題:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace reach_test {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
Class1 formName = new Class1(); // this line compiles OK.
formName.someMethod(); // this line compiles OK.
this.Text = "Some Header"; // this line compiles OK.
}
}
}
這是Class1.cs
文件中的代碼,這是我後添加。我不能達到,例如,Form1.Text
屬性,它駐留在文件Form1.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace reach_test {
public class Class1 {
public string myText;
public Class1() {
myText = "Windows Header";
}
public void someMethod() {
Form1.Text = myText; // this line does not compile!
}
}
}
錯誤消息:An object reference is required for the non-static field, method, or property 'System.Windows.Forms.Control.Text.get'
在其他類中的方法設置名稱,返回的字符串類型,並在它自己的類設置的名稱,而不是似乎是一個更好的選擇。感謝所有回覆。 – ssd 2014-10-27 10:37:26