面向对象的C#编程声明属性

ada*_*m78 0 c# oop variables scope

我有一个班级,在每种方法中我都会反复声明以下几行:

var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
var engines = new ViewEngineCollection();
engines.Add(new FileSystemRazorViewEngine(viewsPath));
Run Code Online (Sandbox Code Playgroud)

如何以及在何处声明它们以便每个方法都可以使用它以便我不必在每个方法中重复写入相同的行?

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();

    }

  }
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 6

你可以让他们成为班级成员:

public class EmailService 
{
    private string viewsPath;
    private ViewEngineCollection engines;

    public EmailService()
    {
        viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
        engines = new ViewEngineCollection();
        engines.Add(new FileSystemRazorViewEngine(viewsPath));
    }

    public void NotifyNewComment(int id)
    {
        var email = new NotificationEmail
        {
            To = "yourmail@example.com",
            Comment = comment.Text
        };

        email.Send();
    }

    // etc.
}
Run Code Online (Sandbox Code Playgroud)

这将在您创建新的时填充变量一次EmailService:

new EmailService()
Run Code Online (Sandbox Code Playgroud)

然后,在该实例上执行的任何方法都将使用当时创建的值.