我试图在我的程序中更好地分离代码重用的关注点,这样我就不会有一个臃肿的控制器来完成所有这些不同的事情。
例如,在我的应用程序中,我有一个用户配置文件,用户可以在其中上传配置文件图片。如果他们不自定义他们的配置文件图片,我将默认配置文件图片设置为一个化身。我通过一种方法来检查它们的配置文件pic字符串是否为null。
我创建了一个名为HelperMethods的文件夹,并创建了一个名为UserHelperMethods的类,该类目前只有一个函数:
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语句是灰色的,所以它没有接收函数调用。有什么想法吗?

发布于 2018-08-30 16:27:04
您需要将helper方法类的实例添加到每个要在其中使用的类中。
UserHelpMethods helper = new UserHelperMethods();然后您可以将其用作:
helper.GetUserProfilePic(foundUser);
...
help.DoSomethingImportant(foundUser);发布于 2018-08-30 16:28:37
你可能想把它变成一个扩展。然后你就可以这样称呼它:
user.GetProfilePic();您必须做的更改是,使类和方法都是静态的,并在参数之前使用this关键字。有点像
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;
}
}发布于 2018-08-30 16:34:38
我会考虑使这些方法是静态的。
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类型的实例。您可以这样调用该方法。
UserHelperMethods.GetUserProfilePic(foundUser);https://stackoverflow.com/questions/52101521
复制相似问题