C# C传递属性作为参数

C# C传递属性作为参数,c#,generics,reflection,C#,Generics,Reflection,我想通过以下方式为“按模型生成”创建辅助对象: 代码盐 控件在编译时的属性名称 从属性属性DisplayName生成html 助手 模型 答复 公共静态无效表格标题器 这个HtmlHelper助手, TModel模型, 参数表达式[]列 { 列中的foreach var列 { var lambda=作为LambdaExpression的列; /* 表1 */ } } 您不能只传递一个属性并找到它,当您传递Model.MyString时,这是不可能的。您只传递一个字符串,被调用的方法无法知道它

我想通过以下方式为“按模型生成”创建辅助对象:

代码盐

控件在编译时的属性名称

从属性属性DisplayName生成html

助手

模型

答复

公共静态无效表格标题器 这个HtmlHelper助手, TModel模型, 参数表达式[]列 { 列中的foreach var列 { var lambda=作为LambdaExpression的列; /* 表1 */ } }
您不能只传递一个属性并找到它,当您传递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
   }
}

解析什么?我的意思是,您传递属性列表以访问要解析的字符串,但是您如何处理解析的值?您的问题到底是什么?您是否在询问如何实现可以接受两个字符串或四个字符串的ParseObject?这叫做重载。我需要解析属性列表。我需要自动完成。应该由编译器进行测试。答案是public void ParseObjectT模型,params Func[]funcs
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 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
   }
}
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);