我知道如何从表单操作表单上的文本框,但我不知道如何从其自己文件中的类操作文本框到表单。
有人可以向我解释一下如何编写委托(delegate)和回调,以便我可以简单地从不同文件中的类调用方法,并从不同的表单更改文本框上的内容吗?
我不知道如何更好地解释这一点。感谢您的帮助!
最佳答案
您的类(class)不应更改表单。
但是,您可以在您的类中创建委托(delegate)或事件,并让您的类在必须采取某些操作时引发该事件。 您的表单可以将事件处理程序附加到该事件,并执行适当的操作。
例如:
class MyClass
{
public event EventHandler DoSomething;
public void DoWork()
{
// do some stuff
// raise the DoSomething event.
OnDoSomething(EventArgs.Empty);
}
protected virtual void OnDoSomething(EventArgs args )
{
// This code will make sure that you have no IllegalThreadContext
// exceptions, and will avoid race conditions.
// note that this won't work in wpf. You could also take a look
// at the SynchronizationContext class.
EventHandler handler = DoSomething;
if( handler != null )
{
ISynchronizeInvoke target = handler.Target as ISynchronizeInvoke;
if( target != null && target.InvokeRequired )
{
target.Invoke (handler, new object[]{this, args});
}
else
{
handler(this, args);
}
}
}
}
并且,在您的表单中,您可以执行以下操作:
MyClass c = new MyClass();
c.DoSomething += new EventHandler(MyClass_DoSomething);
c.DoWork();
private void MyClass_DoSomething(object sender, EventArgs e )
{
// Manipulate your form
textBox1.Text = " ... ";
}
当您想要将一些数据从您的类传递到您的表单时,您可以使用通用的 EventHandler 委托(delegate),并创建您自己的 EventArgs 类,其中包含您的表单所需的信息。
public class MyEventArgs : EventArgs
{
public string SomeData
{ get;
private set;
}
public MyEventArgs( string s )
{
this.SomeData = s;
}
}
当然,您必须在类中使用通用事件处理程序,并将适当的数据传递到您自己的 eventargs 类的构造函数中。 然后,您可以在事件处理程序中使用此数据。
关于c# - 在 C# 中,我如何使用委托(delegate)来操作我创建的自定义类中的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/796914/