首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C#/.NET MVC应用程序中调用另一个类的函数

在C#/.NET MVC应用程序中调用另一个类的函数
EN

Stack Overflow用户
提问于 2018-08-30 16:17:56
回答 5查看 7.4K关注 0票数 1

我试图在我的程序中更好地分离代码重用的关注点,这样我就不会有一个臃肿的控制器来完成所有这些不同的事情。

例如,在我的应用程序中,我有一个用户配置文件,用户可以在其中上传配置文件图片。如果他们不自定义他们的配置文件图片,我将默认配置文件图片设置为一个化身。我通过一种方法来检查它们的配置文件pic字符串是否为null。

我创建了一个名为HelperMethods的文件夹,并创建了一个名为UserHelperMethods的类,该类目前只有一个函数:

代码语言:javascript
复制
namespace HiRatik.Stories.HelperMethods
{
    public class UserHelperMethods
    {
        //checks if the user's profile pic is null and sets it to default pic if it is
        public string GetUserProfilePic(ApplicationUser user)
        {
            if (user.ProfilePic == null)
            {
                user.ProfilePic = "profile_pic_default.png";
            }

            return user.ProfilePic;
        }
    }
}

现在,在控制器的文件夹下,我添加了using HiRatik.Stories.HelperMethods;

并试图从GetUserProfilePic调用公共函数UserController。但是我在实现上出了一个错误。我希望能够将许多与用户相关的通用函数放在另一个类(如UserHelperMethods )中,以清理控制器中的大容量,但在实现上我遗漏了一些东西。顶部的using语句是灰色的,所以它没有接收函数调用。有什么想法吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-08-30 16:27:04

您需要将helper方法类的实例添加到每个要在其中使用的类中。

代码语言:javascript
复制
UserHelpMethods helper = new UserHelperMethods();

然后您可以将其用作:

代码语言:javascript
复制
helper.GetUserProfilePic(foundUser);
...
help.DoSomethingImportant(foundUser);
票数 3
EN

Stack Overflow用户

发布于 2018-08-30 16:28:37

你可能想把它变成一个扩展。然后你就可以这样称呼它:

代码语言:javascript
复制
user.GetProfilePic();

您必须做的更改是,使类和方法都是静态的,并在参数之前使用this关键字。有点像

代码语言:javascript
复制
public static class ApplicationUserExtensions
    {
        //checks if the user's profile pic is null and sets it to default pic if it is
        public static string GetProfilePic(this ApplicationUser user)
        {
            if (user.ProfilePic == null)
            {
                user.ProfilePic = "profile_pic_default.png";
            }

            return user.ProfilePic;
        }
    }
票数 1
EN

Stack Overflow用户

发布于 2018-08-30 16:34:38

我会考虑使这些方法是静态的。

代码语言:javascript
复制
namespace HiRatik.Stories.HelperMethods
{
    public class UserHelperMethods
    {
        //checks if the user's profile pic is null and sets it to default pic if it is
        public static string GetUserProfilePic(ApplicationUser user)
        {
            if (user.ProfilePic == null)
            {
                user.ProfilePic = "profile_pic_default.png";
            }

            return user.ProfilePic;
        }
    }
}

如果助手方法不依赖于UserHelperMethods对象中的任何状态,这将使从任何地方调用方法变得更加容易,因为不再需要创建UserHelperMethods类型的实例。您可以这样调用该方法。

代码语言:javascript
复制
UserHelperMethods.GetUserProfilePic(foundUser);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52101521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档