[英]How do I call a method from another controller?
I have a couple of reusable methods GetChartData() and GetPeopleData(). 我有几个可重用的方法GetChartData()和GetPeopleData()。 They are stored in a controller called CentralData.cs 它们存储在名为CentralData.cs的控制器中
I would like to be able to call any one of these methods from a different controller but I'm not sure how I would do that. 我希望能够从不同的控制器调用这些方法中的任何一个,但是我不确定该怎么做。 Does anyone know how I call a method that is located in another controller? 有谁知道我如何调用另一个控制器中的方法?
If the method was in the same class it would be as simple as: 如果该方法在同一类中,则将非常简单:
MyMethod()
{
GetChartData();
}
So if the method is in a different controller and as sucha different class, how do I call it? 因此,如果该方法位于不同的控制器中并且属于此类,那么该如何调用呢?
You can create an object of Controller
and call the function like a simple class. 您可以创建Controller
对象,然后像简单的类一样调用函数。 I do not think any problems with this approach. 我认为这种方法没有任何问题。 After all, a controller is just a class. 毕竟,控制器只是一类。 eg, 例如,
MyController obj = new MyController();
obj.MyFunction();
You can only call a non-static method from another class if you have a reference of the object. 如果您有对象的引用,则只能从另一个类调用非静态方法。
If you create the second controller somewhere in the first controller, like: 如果您在第一个控制器中的某个位置创建第二个控制器,例如:
ButtonClick(object Sender, EventArgs e) {
CentralData c = new CentralData();
}
you can simply save that reference in a private variable and lateron say 您可以简单地将该引用保存在私有变量中,稍后再说
MyMethod()
{
c.GetChartData();
}
If you create both of them in another class you have to pass the CentralData object to your other Controller like 如果您在另一个类中都创建了它们,则必须将CentralData对象传递给另一个Controller,例如
public static void Main() {
CentralData c = new CentralData();
WindowController w = new WindowController(c);
}
or 要么
public static void Main() {
CentralData c = new CentralData();
WindowController w = new WindowController();
w.c = c;
}
If you mean that you have 2 controller classes: Controller
and OtherController
, then you can access a method located in the second class from the first class like this: 如果您意味着有两个控制器类: Controller
和OtherController
,则可以从第一个类访问位于第二个类中的方法,如下所示:
class Controller
{
public void MethodA()
{
OtherController.MethodB(); // This will work because MethodB is static
// Like shown above you can call a static method from anywhere
}
}
class OtherController
{
public static void MethodB() // <-- Notice "static"
{
// Do stuff
}
}
I hope this is what you were looking for and that this was a sufficient explaination. 我希望这是您想要的,并且已经足够了。 If I am too unclear, then just ask what's confusing. 如果我不太清楚,那就问一下令人困惑的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.