在C#中使用事件处理程序调用方法 [英] Calling the method with the help of event handler in C#

查看:91
本文介绍了在C#中使用事件处理程序调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在不创建对象的情况下调用该方法。



我尝试了什么:



我有两个文件A1.cs和A2.cs,



class A1

{

在这个我正在加载A2,After Again再回到A1。现在页面正在加载完全。



.....

.....

X();



}

class A2

{}



现在我的要求是我需要从A2调用X()方法。不创建对象

I need to call the method without creating the object.

What I have tried:

I have two files A1.cs and A2.cs,

class A1
{
In this i am loading the A2,After Again come back to A1 .Now Page is loading completely.

.....
.....
X();

}
class A2
{}

Now my requirement is i need to call the X() method from A2. Without creating the object

推荐答案

如果声明方法 static,则只能从没有该类实例的类中调用方法即它不需要访问任何基于实例的信息才能工作。



想想汽车片刻:汽车有两个属性:一个颜色和一些轮子。让我们写一个快速的方法来获取它们。

汽车的颜色显然取决于你所指的具体车型:我的车是黑色的,你的车可能是蓝色的,那个汽车现在可能是绿色的,并在一分钟内参考黄色汽车。因此,GetColour需要访问基于实例的信息:
You can only call a method from a class without an instance of that class if the method is declared static i.e. it does not need to access any instance based information in order to work.

Think of cars for a moment: a car has two properties: a colour and a number of wheels. Let's write a quick method to fetch them.
The colour of a car obviously depend on the specific car you refer to: "my car" will be black, "your car" might be blue, "that car" could be green now, and refer to a yellow car in a minute. So GetColour requires access to instance based information:
public Color GetColour()
   {
   return this.Colour;
   }

我们需要汽车的一个实例来使用它:

And we need an instance of the car to use it:

Car myCar == new Mercedes("A180", Color.Black);
Car yourCar = new BMW("6 Series", Colour.Blue);
Console.WriteLine("My car is {0}", myCar.GetColour());
Console.WriteLine("Your car is {0}", yourCar.GetColour());

但是轮子的数量是一个常数 - 它总是四个(因为如果它有两个它就是摩托车!)所以我们不需要访问任何基于实例的信息,它可以是一个静态方法:

But the number of wheels is a constant - it's always four (because if it had two it would be a motorcycle!) So we don't need access to any instance based information, and it can be a static method:

public static int GetNumberOfWheels()
   {
   return 4;
   }

我们在没有实例的情况下使用类名作为前缀:

And we use it without an instance by using the class name as a prefix:

Console.WriteLine("My car has {0} wheels", Car.GetNumberOfWheels());
Console.WriteLine("Your car has {0} wheels", Car.GetNumberOfWheels());





因此,如果X不需要访问任何实例信息,您可以将其声明为 static 并通过类名调用它:

A2.X();

但是如果它需要使用这个根本 - 显式或隐式 - 它不能是 static 因为它是基于实例的信息的访问者。

But if it needs to use this at all - explicitly or implicitly - it can't be static because that is the accessor for instance based information.


这篇关于在C#中使用事件处理程序调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆