传递一个泛型对象并决定在中填充什么

本文关键字:asp Label 什么 填充 决定 对象 泛型 一个 | 更新日期: 2023-09-27 18:16:09

我有一个<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工作正常?

传递一个泛型对象并决定在<asp:Label>中填充什么

您应该使用ReportQuestionReportQuestionTranslation实现的接口:

interface IQuestion
{
    string TitleText;
}

然后,使用以下代码:

public void PopulateLabels(IQuestion item)
{
    lblQuestionTitle.Text = item.TitleText;
}

使用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);
}

ToString()方法应该是这样的:

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

假设我在上面的评论中正确回答了我自己的问题,即字符串将从哪里来

您可以在这些对象上重写ToString(),而不用担心PopulateLabel中的任何转换或类型。