1

我有以下课程:

public class Question {
    public Question() { this.Answers = new List<Answer>(); }
    public int QuestionId { get; set; }
    public string Text { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
}

public class Answer {
    public int AnswerId { get; set; }
    public string Text { get; set; }
}

我有以下有人建议作为检查字符串并删除结尾的方法。我把它放到一个方法中,现在看起来像这样:

    public static string cleanQuestion(string text)
    {
        if (text == null) { return null; }
        else {
            return (Regex.Replace(text, "<p>&nbsp;</p>$", ""));
        }
    } 

我知道如何在问题的文本字段上调用此方法。但是我怎么能在每个答案文本字段上调用该方法呢?

4

5 回答 5

0

您也可以使用 Extension 方法的方法会更方便。

public class Question
{
    public Question() { this.Answers = new List<Answer>(); }
    public int QuestionId { get; set; }
    public string Text { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
}

public static class TextExtension
{
    public static string CleanQuestion(this Question @this)
    {
        if (@this.Text == null) { return null; }
        else
        {
            return (Regex.Replace(@this.Text, "<p>&nbsp;</p>$", ""));
        }
    } 
}


    // Usage:
    Question q1= new Question();
    q1.CleanQuestion();
于 2013-10-14T12:26:32.637 回答
0

如何将属性更改为字段支持的属性:

public class Answer {
    private string _text;

    public int AnswerId { get; set; }
    public string Text
    {
        get { return _text; }
        set { _text = Class.cleanQuestion(value); }
    }
}

方法所在Class的类在哪里static

现在,每次获得答案时Text,都会对其进行清理。

另一方面。如果您希望包含未清理的Text值,除非在某些情况下,您可以get在类上构建一个属性Answer

public string CleanText
{
    get { return Class.cleanQuestion(this.Text); }
}
于 2013-10-14T12:05:32.323 回答
0

您是否尝试过以下操作:

    Question q = new Question();

    foreach (Answer ans in q.Answers) {
        string cleanedText = cleanQuestion(ans.Text);
    }

这将遍历您的问题对象中集合中的每个答案,并使用答案文本的参数调用该方法。

于 2013-10-14T12:06:41.567 回答
0

我想只是通过每个Question

foreach(Anser answer in question.Answers)
  answer.Text = cleanQuestion(answer.Text);

但是,我还要说,也许您应该cleanQuestion()将. 这样,您只需调用,它就会自行处理每个答案。QuestionmethodCleanQuestions()

于 2013-10-14T12:09:05.500 回答
0

如果您想保留原始答案:

问题类:

public List<Answer> CleanAnswers {
    get {
        return Answers.Select(a => a.CleanText()).ToList();
    }
}

答题类:

public string CleanText()
{
    if (this.Text == null) { return null; }
    else {
        return (Regex.Replace(this.Text, "<p>&nbsp;</p>$", ""));
    }
} 
于 2013-10-14T12:10:35.650 回答