c#面向对象编程声明属性

本文关键字:属性 声明 面向对象编程 | 更新日期: 2023-09-27 18:01:18

我有一个类,在每个方法中我重复声明以下几行:

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

c#面向对象编程声明属性

您可以使它们成为类级成员:

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时填充一次变量:

new EmailService()

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