【问题标题】:C# Object Oriented Programming Declaring PropertiesC# 面向对象编程声明属性
【发布时间】: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();

    }

  }

【问题讨论】:

  • 在方法之外但在类中声明它们为公共、私有等。根据需要

标签: c# oop variables scope


【解决方案1】:

你可以让他们成为类级别的成员:

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

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

【讨论】:

  • 只是补充一下(不知道的人),上面例子中的赋值是在构造函数中完成的。
猜你喜欢
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
相关资源
最近更新 更多