如何更改作为对象一部分的集合中的字段的值



我有以下类:

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>$", ""));
        }
    } 

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

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

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

其中Classstatic 方法所在的类。

现在,每次答案Text,它都会被清理干净。

另一方面。如果希望Text包含未清理的值(在某些情况下除外),则可以在 Answer 类上生成 get 属性:

public string CleanText
{
    get { return Class.cleanQuestion(this.Text); }
}

您是否尝试过以下方法:

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

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

我认为只需浏览每个Question

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

但是,我还要说,也许您应该将cleanQuestion()添加到Question类中作为method。这样,您只需拨打CleanQuestions(),它就会自行完成每个答案。

如果你想保留原来的答案:

问题类:

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>$", ""));
    }
} 

你也可以去扩展方法方法会更方便。

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

最新更新