2017-10-17 50 views
-2

我試圖將我的程序分成類以減少混亂和增加可讀性。C#WinForms'this.Controls.Find'在一個單獨的類

在我的一種方法中,我需要在屏幕上找到標籤的位置。

this.Controls.Find工作之前,我都感動到單獨的類,但因爲我不再是同一類的控件執行它不存在了。我嘗試Main.Controls.Find(Main.cs是我的表單被執行和設置的地方),但是這也不起作用,並且我得到錯誤:「非靜態字段,方法或屬性Control需要對象引用。 Controls'「

如何引用控件?我是否需要添加額外的使用語句?

感謝,

喬希

+1

您需要的表單對象的引用。班內容易,移動時不容易。考慮將它傳遞給構造函數。 –

+0

瞭解更多關於['Class'](https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/classes)以及創建對象實例的信息。 –

回答

0

你需要一個參考的形式流傳下來新近出臺的方法(或類)。

之前

public class Main : Form { 

    public void Whatever() { 
     ... 
     this.Controls.Find(...); 
    } 
} 

public class Main : Form { 

    public void Whatever() { 
     ... 
     new Helpers().HelperMethod(this); 
    } 
} 

public class Helpers { 

    public void HelperMethod(Form form) { 
     ... 
     form.Controls.Find 
    } 
} 

public class Main : Form { 

    public void Whatever() { 
     ... 
     new Helpers(this).HelperMethod(); 
    } 
} 

public class Helpers { 

    private Form Form { get; set; } 
    public Helpers(Form form) { 
     this.Form = form; 
    } 

    public void HelperMethod() { 
     ... 
     this.Form.Controls.Find 
    } 
} 
+0

謝謝Wiktor ... –