C#将属性作为params传递



我想用创建按模型生成的助手

  • 代码盐

  • compile时的控件属性名称

  • 从属性属性(DisplayName(生成html

助手

    Html.TableHeaderFor(
        Model, 
        m => m.Name, 
        m => m.Id, 
        m => m.Code,
        m => m.Property1.Name
   );

型号

public class Model
{
    public Model Property1 { get; set; }
    public string Name { get; set; }
    public Guid Id { get; set; }
    [DisplayName("Item code")]
    public int Code { get; set; }
}

回答

public static void TableHeaderFor<TModel>(
   this HtmlHelper helper, 
   TModel model, 
   params Expression<Func<TModel, object>>[] columns)
{
    foreach (var column in columns)
    {
        var lambda = column as LambdaExpression;
        /*
        Table gereration 
        */
    }
}

你不能只传递一个属性就找到它,这是不可能的(当你传递Model.MyString时,你只是传递一个字符串,被调用的方法无法知道它是Model的一部分,也无法知道它被命名为MyString,这不可能,句号,不要再看了(

如果你愿意更改调用语法,你可以做的是(取决于你需要什么(传入一个或多个lamda函数或表达式的参数(取决于是你只想让IntelliSense&传递数据,还是你还需要在被调用的方法中找出属性名(

public void ParseObject<T>(T model, params Func<T,string>[] funcs)
{
   foreach(var f in funcs)
   {
      var string = f(model); // do whatever you want with string here
   }
}

或者表达式方法(表达式表示运行时的代码,也就是说,简化"半编译代码",以便您仍然可以查看它(:

public void ParseObject<T>(T model, params Expression<Func<<T,string>>[] exprs)
{
   foreach(var e in exprs)
   {
      var string = (e.Compile())(model); // do whatever you want with string here
      var targetMember = ((System.Linq.Expressions.MemberExpression) e.Body).Member; // warning, this will only work if you're properly calling the ParseObject method with the exact syntax i note bellow, this doesn't check that you're doing nothing else in the expressions, writing a full parser is way beyond the scope of this question
     // targetMember.Name will contain the name of the property or field you're accessing
     // targetMember.ReflectedType will contain it's type
   }
}

编辑:用示例调用方法的示例方法,注意这个方法不仅适用于Model,而且适用于任何类!

ParseObject(m, m=>m.Property1, m=>m.Property2); // will work with any number of properties you pass in and full IntelliSense.
public void ParseObject(Model m, params Expression<Func<Model, object>>[] args)
{
  ...
}

从每个表达式中,您可以检查主体并计算道具信息。

这样称呼它:

ParseObject(m, o => o.Property1, o => o.Property2);

相关内容

  • 没有找到相关文章