实现一个扩展方法

本文关键字:一个 扩展 方法 实现 | 更新日期: 2023-09-27 17:50:51

我有这样的代码:

 namespace Zinc.Web.Extensions.DataModel.Training
 {
   public static class TrainingModuleProgressStateDataModelExtentions
   { 
      public static string GetHintText(String aString)
      {
         //must still make up astring here
         return aString;
       }
   }
 }
 namespace Zinc.DataModels.Training
 {
    public class TrainingModuleProgressStateDataModel
    {
      public IEnumerable<UserTrainingPointsDataModel> UserTrainingPoints { get; set; }
    }
  }
  public class UserTrainingPointsDataModel
  {
    public virtual int InteractionType { get; set; }
    public virtual int Points { get; set; }
    public virtual string Name { get; set; }
    public virtual string IncentiveTrainingModuleOptionName { get; set; }
  }

在我的存储库中我添加到UserTrainingPoints:

 string RawPoints = row["RawPoints"].ToString();
 string[] rawPoints = RawPoints.Split(new char[] { '|' });
 List<UserTrainingPointsDataModel> points = new List<UserTrainingPointsDataModel>();
 foreach (var RawPoint in rawPoints)
 {
   string[] entry = RawPoint.Split(new char[] { ',' });
   var point = new UserTrainingPointsDataModel();
   point.Name = entry[0];
   point.Points = Convert.ToInt32(entry[1]);
   point.InteractionType = Convert.ToInt32(entry[2]);
   point.IncentiveTrainingModuleOptionName = entry[3];
   points.Add(point);  
 }
 trainingModuleProgressState.UserTrainingPoints = points;
 data.Add(trainingModuleProgressState);

在我看来,我需要调用扩展方法,它将在UserTrainingPoints中获取值,以组成一个字符串,然后我将在工具提示中显示。

我的问题是我如何实现扩展方法,以便我可以在我的视图中调用它?

my view code:

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Zinc.Models.Training.TrainingModuleProgressStateDataModelResults>" %>
 <%@ Import namespace="Zinc.Web.Extensions.DataModel.Training" %> //added this
  <% if (module.HasAssessment)
  { %>
     <div class="<%: moduleStateClass %>">&nbsp;</div>
     <div class="<%: moduleScoreClass %>"><%: module.ModuleScore %>%</div>
     <% Zinc.Web.Extensions.DataModel.Training.TrainingModuleProgressStateDataModelExtentions.GetHintText(module.UserTrainingPoints); %>  //still not correct here

实现一个扩展方法

由于UserTrainingPointsIEnumerable<UserTrainingPointsDataModel>,我认为您的扩展方法签名应该是

public static string GetHintText(this IEnumerable<UserTrainingPointsDataModel> points)
{
    string aString;
    //must still make up astring here
    return aString;
}

那么你可以这样命名

module.UserTrainingPoints.GetHintText();

访问扩展方法的方式与您通常使用的方式相同。但是,您应该注意使用@using关键字对添加扩展的名称空间进行引用。