从另一个文件 C# 调用另一个类的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16686511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling method from another class from another file C#
提问by Tudor Gafiuc
I have declared a namespace in Feed.aspx.cs . This namespace contains a class and this class contains a method: Feed.aspx.cs
我在 Feed.aspx.cs 中声明了一个命名空间。这个命名空间包含一个类,这个类包含一个方法: Feed.aspx.cs
namespace GetUser
{
public class MyFeedClass
{
public string getUserID()
{
MembershipUser user = Membership.GetUser(HttpContext.Current.User.Identity.Name);
HttpContext.Current.Session["x"] = user.ProviderUserKey.ToString();
string test = (string)HttpContext.Current.Session["x"];
return test;
}
}
}
}
Now, from MyPage.aspx.cs, I'd like to call the getUserID() method. How can I do that?
现在,从MyPage.aspx.cs,我想调用 getUserID() 方法。我怎样才能做到这一点?
采纳答案by Carlos Landeras
I guess you are using Asp.NET?
我猜你在使用 Asp.NET?
You should create a new class inside your add_code folder. Move that namespace and the class inside the new created class
您应该在 add_code 文件夹中创建一个新类。将该命名空间和类移动到新创建的类中
Then call it from your Feed.aspx.cs:
然后从您的 Feed.aspx.cs 调用它:
GetUser.MyFeedClass myfeed = new GetUser.MyFeedClass();
string result = myfeed.getUserID();
回答by iceheaven31
Make sure you include the namespace in your code-behind:
确保在代码隐藏中包含命名空间:
using GetUser;
Make the public function a static one in the MyFeedClass:
使公共函数成为 MyFeedClass 中的静态函数:
public static string getUserID() {...}
Then in your aspx.cs page you can now try to do:
然后在您的 aspx.cs 页面中,您现在可以尝试执行以下操作:
string userId = MyFeedClass.getUserID();

