![](/img/trans.png)
[英]How can I use a class and constructor in a another class, method and store them to my list? C#
[英]C# How can I Learn Class that Call My Method in another Class
public class Form1:Form
{
public Form1()
{
}
Form1_Load(object Sender,EventArgs e)
{
SampleClass Sample=new SampleClass();
Sample.MyMethod();
}
}
這是我項目中的第一個 class ,第二個是
大家好
public class SampleClass
{
public void MyMethod()
{
//When Form1 or another class call this Method
//I want to know it for example
Caller.Title="Deneme";
//
//Unless send parametr.How Can I learn Caller class and i change it items?
}
}
調用者必須將對自身的引用傳遞給方法。
public void MyMethod(Form caller)
{
caller.Title="Deneme";
}
或者,如果您不希望SampleClass
與表格 class 有強鏈接 - 它可能位於不引用 Windows 表格的單獨程序集中,您可以傳入一個使用傳入的正確字符串調用的操作。
Form1_Load(object Sender,EventArgs e)
{
SampleClass Sample=new SampleClass();
Sample.MyMethod( title => this.Title = title );
}
和
public void MyMethod(Action<string> setTitle )
{
setTitle ("Deneme");
}
編輯解釋代表
動作參數
MyMethod 上的 Action 參數本質上是一個包含可運行代碼的變量。 (要完全理解這個概念確實需要一點頭緒。)類型的<string>
部分表示我們可以將字符串傳遞給將要運行的代碼。
然后這條線
setTitle ("Deneme");
正在調用此代碼並將文本“Deneme”傳遞給它。 這是您要將 Windows 標題設置為的文本。 現在, MyMethod
方法實際上並不知道它將 Windows 標題設置為該文本。 這已成為調用者的責任。 (如果您希望MyMethod
絕對確定它正在設置表單的標題,那么第一個解決方案就是您想要的解決方案。)
打電話
方法調用的調用者
MyMethod( title => this.Title = title );
MyMethod 的參數是:
title => this.Title = title
這是您傳遞給 Action 變量的代碼。 =>
左側的title
是在調用代碼時將具有傳遞給它的字符串的變量,而=>
右側的內容是被調用的代碼。
因此,當表單調用 MyMethod 時,它表示我想要該字符串,並且我將為其設置標題。
這樣做的美妙之處在於 MyMethod 不知道表單。 如果您想在編寫控制台應用程序時重用您的 class,您可以調用:
MyMethod ( title => Console.WriteLine (title) );
MyMethod 根本不需要動!
你可以試試:
public class SampleClass
{
public void MyMethod(Form sender)
{
sender.Text = "title";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.