![](/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.