1

我有一个<asp:Label> 我希望根据我传递给它的通用对象来填充。

目前我有以下代码: -

    private void PopulateEnglishQuestion(int questionId)
    {
        ReportQuestion reportQuestion = questionsBll.GetReportQuestions().Where(x=> x.ReportQuestionId == questionId).FirstOrDefault();
        PopulateLabels(reportQuestion);
    }

    private void PopulateTranslatedQuesiton(int questionId)
    {
        ReportQuestionTranslation reportQuestionTranslation = questionsBll.GetReportQuestionsTranslation().Where(x => x.QuestionId == questionId).FirstOrDefault();
        PopulateLabels(reportQuestionTranslation);
    }

    private void PopulateLabels<T>(T item)
    {
        lblQuestionTitle.Text = typeof (T) == typeof (ReportQuestion)
                                    ? ((ReportQuestion) (item)).ReportQuestionTitle
                                    : ((ReportQuestionTranslation) (item)).ReportQuestionTitleTrans; 
    }

如何让 PopulateLabels 方法正常工作?

4

4 回答 4

5

您应该同时使用接口ReportQuestionReportQuestionTranslation实现:

interface IQuestion
{
    string TitleText;
}

然后,使用以下代码:

public void PopulateLabels(IQuestion item)
{
    lblQuestionTitle.Text = item.TitleText;
}
于 2013-05-29T16:42:53.413 回答
3

使用interface.

public interface IQuestion
{
    string Title { get; }
}

public class ReportQuestion : IQuestion
{
    public string Title { get { return ReportQuestionTitle; } }
}

public class ReportQuestionTranslation: IQuestion
{
    public string Title { get { return ReportQuestionTitleTrans; } }
}

private void PopulateLabels(IQuestion item)
{
    lblQuestionTitle.Text = item.Title;
}

或者使用方法重载:

public void PopulateTitle(ReportQuestion question)
{
    lblQuestionTitle.Text = question.ReportQuestionTitle;
}

public void PopulateTitle(ReportQuestionTranslation question)
{
    lblQuestionTitle.Text = question.ReportQuestionTitleTrans;
}

不推荐:

public class QuestionTitleFormatter
{
    public string GetTitle(object question)
    {
        if(question is ReportQuestion)
            return ((ReportQuestion)question).ReportQuestionTitle;

        if(question is ReportQuestionTranslation)
            return ((ReportQuestionTranslation)question).ReportQuestionTitleTrans;

        throw new NotImplementedException(string.Format("{0} is not supported", questionType.Name);
    }
}

public void PopulateTitle(object question)
{
    var formatter = new QuestionTitleFormatter();
    lblQuestionTitle.Text = formatter.GetTitle(question);
}
于 2013-05-29T16:44:47.730 回答
1

ToString() 方法是这样的:

class ReportQuestion {
    public override string ToString() { return ReportQuestionTitle; }
    ...
}

class ReportQuestionTranslation{
    public override string ToString() { return ReportQuestionTitleTrans; }
    ...
}

假设我在上面的评论中正确回答了我自己的问题,询问字符串来自何处。

于 2013-05-29T17:26:58.100 回答
0

您可以只覆盖这些对象上的 ToString(),而不必担心 PopulateLabel 中的任何转换或类型。

于 2013-05-29T16:50:43.987 回答