C#传递属性为params

时间:2014-06-10 07:30:46

标签: c# generics reflection

我想用模型创建帮助器:

  • 代码盐

  • 控制在complie time属性名称

  • 从属性属性(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 
        */
    }
}

2 个答案:

答案 0 :(得分:2)

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

如果你愿意更改你的调用语法,你可以做什么(取决于你需要的)传递一系列lamda函数或表达式(取决于你是否只需要IntelliSense&amp;传递数据或者你还需要在被调用的方法中找出属性名称)

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.

答案 1 :(得分:1)

public void ParseObject(Model m, params Expression<Func<Model, object>>[] args)
{
  ...
}

从每个表达式中,您可以检查身体并找出道具信息。

这样称呼:

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