【发布时间】:2016-08-08 19:53:58
【问题描述】:
我有一个类,在每个方法中我重复声明以下几行:
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
我如何以及在哪里声明它们,以便每个方法都可以使用它,这样我就不必在每个方法中重复写同一行?
public class EmailService
{
public EmailService()
{
}
public void NotifyNewComment(int id)
{
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
var email = new NotificationEmail
{
To = "yourmail@example.com",
Comment = comment.Text
};
email.Send();
}
public void NotifyUpdatedComment(int id)
{
var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
var email = new NotificationEmail
{
To = "yourmail@example.com",
Comment = comment.Text
};
email.Send();
}
}
【问题讨论】:
-
在方法之外但在类中声明它们为公共、私有等。根据需要