在C#中提取方法以在整个项目中使用

时间:2012-05-29 21:31:42

标签: c# oop methods

在这里原谅冗长的代码,我也意识到对于任何面向对象的开发人员来说这可能是一个非常基本的基本问题,但我是一个深入了解.NET的前端开发人员,并试图了解具有实际示例的类和方法。我已经阅读了解释这些内容的资源,但却立即陷入了现实世界代码的复杂性。

基本上我有一堆方法可以为网页添加评论并操纵状态(标记为垃圾邮件,删除等)。其中许多方法都称为“EmailNotification”方法,该方法在每个阶段向管理员发送电子邮件。它很棒。

但是,我想在项目的其他地方使用'EmailNotification'方法,从另一个.cs文件中调用它。当我尝试这样做时,它无法识别该方法,因为(我认为!?)它不是一个公共静态方法。

有人可以向我解释如何提取EmailNotification方法,以便我可以在代码周围的不同位置使用它吗?我已经尝试在其中创建一个使用此方法的新类,但我无法让它工作。

using System;
using System.Net.Mail;

namespace UComment.Domain
{
public class Comment
{
    public delegate void CommentCreatedEventHandler(Comment sender, EventArgs e);
    public delegate void CommentDeletedEventHandler(Comment sender, EventArgs e);
    public delegate void CommentSpamEventHandler(Comment sender, EventArgs e);
    public delegate void CommentApprovedEventHandler(Comment sender, EventArgs e);

    public static event CommentCreatedEventHandler CommentCreated;
    public static event CommentDeletedEventHandler CommentDeleted;
    public static event CommentSpamEventHandler CommentSpam;
    public static event CommentApprovedEventHandler CommentApproved;

    protected virtual void OnCommentCreated(EventArgs e)
    {
        if (CommentCreated != null) CommentCreated(this, e);
    }

    protected virtual void OnCommentSpam(EventArgs e)
    {
        if (CommentSpam != null) CommentSpam(this, e);
    }

    protected virtual void OnCommentApproved(EventArgs e)
    {
        if (CommentApproved != null) CommentApproved(this, e);
    }

    protected virtual void OnCommentDelete(EventArgs e)
    {
        if (CommentDeleted != null) CommentDeleted(this, e);
    }


    public int Id { get; set; }
    public int ParentNodeId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Website { get; set; }
    public bool Spam { get; set; }
    public bool Approved { get; set; }
    public DateTime Created { get; set; }
    public string CommenText { get; set; }
    public int StatusId { get; set; }

    public Comment(int id)
    {
        Id = id;
        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);
        var reader = sqlHelper.ExecuteReader("select * from Comment where id = @id",
                                             sqlHelper.CreateParameter("@id", id));

        if(!reader.HasRecords) throw new Exception(string.Format("Comment with id {0} was not found", id));

        reader.Read();

        Name = reader.GetString("name");
        ParentNodeId = reader.GetInt("nodeid");
        Email = reader.GetString("email");
        Website = reader.GetString("website");
        Approved = reader.GetBoolean("approved");
        Spam = reader.GetBoolean("Spam");
        Created = reader.GetDateTime("created");
        CommenText = reader.GetString("comment");
        StatusId = reader.GetInt("statusid");
    }

    private Comment()
    {
    }

    /// <summary>
    /// Set as approved, mark as Not Spam - ignore HAM status
    /// </summary>
    public void MarkAsApproved()
    {
        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);
        sqlHelper.ExecuteNonQuery(
             "update comment set approved = 1, spam = 0, statusid = 2 where id = @id",
             sqlHelper.CreateParameter("@id", Id));

        OnCommentApproved(EventArgs.Empty);

        // Send approval email
        EmailNotification(1);

    }

    /// <summary>
    /// Remove approval status. Ignore Spam and Ham states
    /// </summary>
    public void MarkAsNotApproved()
    {
        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);
        sqlHelper.ExecuteNonQuery(
             "update comment set approved = 0, statusid = 3 where id = @id",
             sqlHelper.CreateParameter("@id", Id));

        OnCommentApproved(EventArgs.Empty);

        // Send rejection email
        EmailNotification(2);
    }



    /// <summary>
    /// Spam cannot be ham or approved
    /// </summary>
    public void MarkAsSpam()
    {
        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);
        sqlHelper.ExecuteNonQuery(
             "update comment set spam = 1, ham = 0, approved = 0, statusid = 3 where id = @id",
             sqlHelper.CreateParameter("@id", Id));

        OnCommentSpam(EventArgs.Empty);

        // No email notification required - spammer not worthy of a reason for rejection
    }


    /// <summary>
    /// Ham is "not spam" - approved comments from Akismet. 
    /// </summary>
    public void MarkAsHam()
    {
        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);
        sqlHelper.ExecuteNonQuery(
           "update comment set spam = 0, ham = 1 where id = @id",
           sqlHelper.CreateParameter("@id", Id));

        // No email notification required, simply marking spam as ham
    }

    public void Delete()
    {
        if (Id < 1) return;

        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);
        sqlHelper.ExecuteNonQuery("delete from comment where id = @id", sqlHelper.CreateParameter("@id", Id));

        Id = -1;
        OnCommentDelete(EventArgs.Empty);

        // Permanent deletion
    }

    public void Reject()
    {
        if (Id < 1) return;

        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);
        sqlHelper.ExecuteNonQuery("update comment set statusid = 3 where id = @id", sqlHelper.CreateParameter("@id", Id));

        //Id = -1;
        //OnCommentDelete(EventArgs.Empty);

        // Send rejection email
        EmailNotification(2);
    }




    public static Comment MakeNew(int parentNodeId, string name, string email, string website, bool approved, bool spam, DateTime created, string commentText, int statusId)
    {

        var c = new Comment
            {
                ParentNodeId = parentNodeId,
                Name = name,
                Email = email,
                Website = website,
                Approved = approved,
                Spam = spam,
                Created = created,
                CommenText = commentText,
                StatusId = statusId
            };

        var sqlHelper = DataLayerHelper.CreateSqlHelper(cms.GlobalSettings.DbDSN);

        c.Id = sqlHelper.ExecuteScalar<int>(
            @"insert into Comment(mainid,nodeid,name,email,website,comment,approved,spam,created,statusid) 
                values(@mainid,@nodeid,@name,@email,@website,@comment,@approved,@spam,@created,@statusid)",
            sqlHelper.CreateParameter("@mainid", -1),
            sqlHelper.CreateParameter("@nodeid", c.ParentNodeId),
            sqlHelper.CreateParameter("@name", c.Name),
            sqlHelper.CreateParameter("@email", c.Email),
            sqlHelper.CreateParameter("@website", c.Website),
            sqlHelper.CreateParameter("@comment", c.CommenText),
            sqlHelper.CreateParameter("@approved", c.Approved),
            sqlHelper.CreateParameter("@spam", c.Spam),
            sqlHelper.CreateParameter("@created", c.Created),
            sqlHelper.CreateParameter("@statusid", c.StatusId));

        c.OnCommentCreated(EventArgs.Empty);

        if (c.Spam)
        {
            c.OnCommentSpam(EventArgs.Empty);
        }

        if (c.Approved)
        {
            c.OnCommentApproved(EventArgs.Empty);
        }

        return c;
    }

    public override string ToString()
    {
        return @"ParentNodeId " + ParentNodeId + @"
        Name " + Name + @"
        Email " + Email + @"
        Website " + Website + @"
        Approved " + Approved + @"
        Spam " + Spam + @"
        Created "+ Created + @"
        CommenText " + CommenText + Environment.NewLine;
    }


    /// <summary>
    /// Send email notification
    /// </summary>
    public void EmailNotification(int notificationType)
    {

        var uCommentAdminEmail = Config.GetUCommentSetting("uCommentAdminEmail");

        MailAddress to = null;
        MailAddress from = new MailAddress(uCommentAdminEmail);
        string subject = null;
        string body = null;

        switch (notificationType)
        {
            case 1:
                // Comment approved
                to = new MailAddress("me@mydomain.com");
                subject = "Comment approved";
                body = @"The comment you posted has been approved";
                break;
            case 2:
                // Comment rejected
                to = new MailAddress("me@mydomain.com");
                subject = "Comment rejected";
                body = @"The comment you posted has been rejected";
                break;
        }

        MailMessage message = new MailMessage(from, to);
        message.Subject = subject;
        message.Body = body;
        SmtpClient client = new SmtpClient();           

        try
        {
            client.Send(message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught in EmailNotification: {0}", ex.ToString());
        }
        finally
        {
            //
        }


    }


}
}

感谢任何人们的指点!

5 个答案:

答案 0 :(得分:3)

你可以:

  1. 将其提取为静态类
  2. 上的静态方法
  3. 创建具有实例方法的单例类
  4. 为MessageSender创建一个类和接口,并使用DI将其注入需要的位置。
  5. 这取决于项目的规模:对于小项目1.可能就足够了,对于大而复杂(如果你有DI),则需要3个。

答案 1 :(得分:2)

你的班级做了太多事情!

将它拆分为不同的类型,每个类型都必须根据Separation of concerns解决一类问题。

发送电子邮件的同样的事情,创建一个EmailSender类(或其他名称)并在那里集中Send方法。

您还可以创建一个界面(例如ISmtpClientFactory)以传递给EmailSender类,以抽象具体系统来发送电子邮件并改善测试体验。

只有在您真正发送电子邮件的生产环境中,在测试环境中您才可以使用虚假工厂来模拟发送。

public class EmailSender
{
    private readonly ISmtpClientFactory factory;

    public EmailSender(ISmtpClientFactory factory)
    {
        this.factory = factory;
    }

    public void Send(MailMessage message)
    {
        using (var client = factory.Create())
        {
            using (message)
            {
                client.Send(message);
            }
        }
    }
}

new EmailSender(new SmtpClientFactory()).Send(AdviceMessageFactory.Create(...));

答案 2 :(得分:2)

这里有一个公共方法,但因为它没有被声明为静态方法(public static void EmailNotification ...),所以如果不创建它所在的类的实例就不能使用它。

using System;

namespace UComment.Domain
{
    public class MyOtherClass
    {
         public void MyMethod()
         {
             Comment c = new Comment();
             c.EmailNotification(1);
         }
    }
}

你可以声明方法static,它可以让你像这样调用它:

using System;

namespace UComment.Domain
{
    public class MyOtherClass
    {
         public void MyMethod()
         {
             Comment.EmailNotification(1);
         }
    }
}

如果您尝试从不同的命名空间中使用它,那么您需要通过using语句或通过指定内联的完整命名空间来包含命名空间。

using System;
using UComment.Domain;

namespace UComment.OtherNamespace
{
    public class MyOtherClass
    {
         public void MyMethod()
         {
             Comment c = new Comment();
             c.EmailNotification(1);
         }
    }
}

或者

using System;

namespace UComment.OtherNamespace
{
    public class MyOtherClass
    {
         public void MyMethod()
         {
             UComment.Domain.Comment c = new UComment.Domain.Comment();
             c.EmailNotification(1);
         }
    }
}

您认为如果您希望将此作为一种常用方法,那么它是正确的,它应独立于Comment类。我刚刚描述的相同限制适用于这样做。此外,您必须确保新类中包含任何适当的using语句,并且还要考虑EmailNotification中的依赖项。

答案 3 :(得分:0)

你可以将它放在它自己的类中(就像你已经尝试过的那样)并使方法保持静态。

如果这个新类是EmailHelper,你可以调用这样的方法:

EmailHelper.EmailNotification(1);

根据新类的命名空间,您可能还需要在您使用它的每个文件的顶部使用using语句。

答案 4 :(得分:0)

它看起来不应该导致任何问题如果你创建一个(公共)类并在其中有该方法。该方法应该接受发送电子邮件所需的所有属性。您可以创建该类的实例并调用该方法。