C# 表达式<;Func<;t模型,t属性>&燃气轮机;作为对象初始化的属性?

C# 表达式<;Func<;t模型,t属性>&燃气轮机;作为对象初始化的属性?,c#,lambda,properties,expression,C#,Lambda,Properties,Expression,我的表达式不太好,我想对它们进行改进,所以我想知道是否有人能为我解释一下,是否可以在类中创建一个属性,在实例化过程中可以给它一个值,如下所示: new Column<Product>{ ColumnProperty = p => p.Title}; public class Column<TModel> { public Expression<Func<TModel, TProperty>> ColumnProperty {

我的表达式不太好,我想对它们进行改进,所以我想知道是否有人能为我解释一下,是否可以在类中创建一个属性,在实例化过程中可以给它一个值,如下所示:

new Column<Product>{ ColumnProperty = p => p.Title};
public class Column<TModel>
{
        public Expression<Func<TModel, TProperty>> ColumnProperty { get; set; }
}
对于这样的类:

new Column<Product>{ ColumnProperty = p => p.Title};
public class Column<TModel>
{
        public Expression<Func<TModel, TProperty>> ColumnProperty { get; set; }
}
公共类列
{
公共表达式列属性{get;set;}
}
它背后的基本思想是,我从一堆类似这样的列对象创建一个网格

List<Product> productList = GetProductsFromDb();
List<Column> columnList = new List<Column>();

columnList.Add(new Column<Product> {ColumnProperty = p => p.ProductId, Heading = "Product Id"});
columnList.Add(new Column<Product> {ColumnProperty = p => p.Title, Heading = "Title"});

Grid myGrid = new Grid(productList, columnList);
List productList=GetProductsFromDb();
List columnList=新列表();
Add(新列{ColumnProperty=p=>p.ProductId,Heading=“Product Id”});
Add(新列{ColumnProperty=p=>p.Title,Heading=“Title”});
网格myGrid=新网格(productList,columnList);
这可能不是最整洁/最简单的方法,但我想知道是否可以这样做,因为我想提高我对表达式的理解,并且我喜欢能够使用强类型值而不是字符串文本,这样做会更好

如有任何想法、想法或闲谈,将不胜感激

干杯
Rob

好吧,我刚刚灵机一动,将TProperty更改为dynamic,现在我可以这样做了,我想我回答了我自己的问题,但我很想听听其他人对这种方法利弊的看法:

foreach(Product p in productList)
{
    var value = column.ColumnProperty.Compile().Invoke(p);
}
其实

如果我把我的财产换成

public Func<TModel, dynamic> ColumnProperty { get; set; }

当您定义类似于
Func
的内容时,意味着有一个方法采用TModel类型并返回TProperty类型。那么lambda表达式是什么

p => p.ProductId 
返回属性的值,而不是属性本身

要使此语法起作用,您可以按如下方式定义
ColumnProperty

public Expression<Func<TModel, object>> ColumnProperty { get; set; }
公共表达式列属性{get;set;}

然后,您可以从表达式树中提取详细信息。

Hey idursun-谢谢这也有用-我使用了dynamic而不是object,但结果是sameobject在用于基本值(例如int)时会导致异常。在所有情况下使用动态都有效表达方法是一种体面的方法。我认为
dynamic
需要更多的开销,但可能会产生微不足道的影响。动态对象在后台维护对象成员的字典。