如何在C#中的不同页面中调用相同的方法 [英] How to call same method in different page in C#

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

问题描述



我在一个页面中定义了一个方法(SaveData)。我想将同一个方法(SaveData)调用到其他页面。如何在C#中不同页面调用相同的方法

解决方案

除非两个页面相关(第二页是从第一页派生的)或方法是 static ,你不能 - 你需要一个包含该方法的页面实例才能调用它。

如果它是 static ,你最好将它声明为App_Code文件夹中utilities类的一部分,并在两个页面中从那里调用它。


你可以通过使用该类的实例来实现。或者,如果方法声明为 static ,则不必创建该类的实例,您可以直接仅使用类名称调用该方法。



-KR


1。上课。访问修饰符应该是公共的。

2.编写你的方法。访问修饰符应该是公共的。

3.从你的任何页面调用。打电话给你创建该类的对象。



< pre lang =c#> public A类{
public void SaveData( int a, string b){
// 代码在这里
}

}







来自页面的电话:



 A()aObj =  new  A(); 
aObj.SaveData( 1 ' parm ');





希望它有效。


Hi,
I have one method(SaveData) defined in one page.I want to call same method(SaveData) to other page. how to call same method in different page in C#

解决方案

Unless the two pages are related (the second page is derived from the first) or the method is static, you can't - you need an instance of the page that contains the method in order to call it.
And if it's static, you would be much better off declaring it as part of a "utilities" class in your App_Code folder and calling it from there in both pages.


You can do it by using instance of that class. Or if the method is declared as static, you do not have to create the instance of that class, you can directly call that method using class name only.

-KR


1. Make a class. access modifier should be public.
2. Write your method. access modifier should be public.
3. Call from your any page.To call you have create an object of that class.

public Class A{ 
public void SaveData(int a, string b){
//Code goes here
}

}




call from page:

A() aObj = new A();
aObj.SaveData(1,'parm');



Hope it works.


这篇关于如何在C#中的不同页面中调用相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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