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

时间:2016-08-08 19:53:59

标签: c# oop variables scope

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

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

    }

  }

1 个答案:

答案 0 :(得分:6)

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

AccountManager.rb:63: syntax error, unexpected end-of-input, expecting keyword_end

这会在您创建新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. } 时填充变量:

EmailService

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