C# 从不使用';我无法接触到它们
我想从通常无法访问的类中访问某些表单元素。请允许我举例说明这个问题C# 从不使用';我无法接触到它们,c#,visual-studio,C#,Visual Studio,我想从通常无法访问的类中访问某些表单元素。请允许我举例说明这个问题 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.I
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Collections;
namespace MyApp {
public partial class MyApp : Form
{
public MyApp()
{
InitializeComponent();
// Code
}
public void updateLabel(string message)
{
myLabel.Text = message;
}
}
public class NewClass
{
public NewClass()
{
// I want to call updateLabel("My message") here, but 'MyApp.updateLabel("My message");' didn't work even though I made updateLabel public
}
}
}
我如何处理这个问题?我对C#比较陌生,但我有C、PHP、Java和JavaScript方面的经验。我正在使用Visual C#2010 Express。您需要将
MyApp
类的实例传递给NewClass
类。然后,您可以在
MyApp
实例上调用UpdateLabel
,而无需公开标签。由于UpdateLabel是MyApp中的非静态成员方法,因此在调用MyApp的任何实例方法之前,您需要创建MyApp的实例
在NewClass中使用以下代码行:
MyApp myapp = new MyApp();
myapp.updateLabel("Hello World");
我假设MyApp类已经实例化,在这种情况下,您必须将引用传递给NewClass(可能在构造函数之上),正如前面提到的SLaks一样。可能是这样,下面的技术将非常有用。它可以使用
操作
或函数
:
[Test]
public void ActionsTest()
{
var parent = new Parent();
parent.Child.RaiseCallFromParent();
parent.Child.RaiseCallInParent();
}
public class Parent
{
private readonly Child _child = new Child();
public Parent()
{
Child.ActionToCallMethodFromParent = methodCalledFromChild;
Child.ActionToBeCalledInParent += actionCalledInParent;
}
public Child Child
{
get { return _child; }
}
private void actionCalledInParent()
{
Console.WriteLine("It is called in parent on child initiative.");
}
private void methodCalledFromChild()
{
Console.WriteLine("It is called from child");
}
}
public class Child
{
public Action ActionToCallMethodFromParent;
public Action ActionToBeCalledInParent;
public void RaiseCallFromParent()
{
//This works in cases when you need to consume something from Parent but here you cannot take it directly
if (ActionToCallMethodFromParent != null)
ActionToCallMethodFromParent();
}
public void RaiseCallInParent()
{
//This works like an event
if (ActionToBeCalledInParent != null)
ActionToBeCalledInParent();
}
}
这是我自己提出的解决方案。我将
myLabel
作为参数传递给需要访问标签的类构造函数,如下所示:
电话:
NewClass newClassObj = new NewClass(myLabel);
班级:
public class NewClass
{
public NewClass(Label myLabel)
{
myLabel.Text = "Hello world!";
}
}
除非这是一种糟糕的编程实践,否则我更喜欢这种解决方案。想法?最好从您自己的类中引发事件,然后在表单中捕获它并从那里更新控件,这样您就不会将逻辑连接到特定的UI元素。将
public void updatelabel(string message)
更改为public static void updatelabel(string message)
然后从newclass
访问它,就像myapp.updatelabel(message)
一样
当然,您必须使用myapp将表单元素添加到新类的顶部。除了让
NewClass
访问整个myapp
类之外,没有其他方法访问表单元素吗?我还是个新手,但听起来不太优雅。这是一种常见的做法吗?当您的答案(甚至是问题)中包含代码时,建议采用这种格式。(它是“{}”图标。):-)