我的表达不太好,我想改进它们,所以我想知道是否有人可以为我解释是否可以在类中创建一个属性,该属性可以在实例化期间被赋予值,如下所示:
new Column<Product>{ ColumnProperty = p => p.Title};
或者更好(但是 来推动它
new Column {ColumnProperty = p => p.Title};
我想我正在用一个类似这样的类
public class Column<TModel>
{
public Expression<Func<TModel, TProperty>> ColumnProperty { get; set; }
}
:它背后的基本思想是我从一堆像这样的 Column 对象创建一个网格。
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);
这可能不是最简洁/最简单的方法,但我有兴趣知道它是否可以完成,因为我想提高对表达式的理解,并且我喜欢能够使用强类型值而不是字符串文字,这样更好一起工作。
任何想法、想法、漫谈将不胜
感激
抢
My expression aren't great and I would like to improve on them so I am wondering if someone could explain for me if it possible to create a property in a class that can be given a value during instantiation like this:
new Column<Product>{ ColumnProperty = p => p.Title};
or better still (but I think I am pushing it)
new Column {ColumnProperty = p => p.Title};
with a class something like this:
public class Column<TModel>
{
public Expression<Func<TModel, TProperty>> ColumnProperty { get; set; }
}
The basic idea behind it is that I create a Grid from a bunch of Column objects something like this.
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);
This may not be the tidiest/easiest way to do this but I am interested in knowing whether it can be done as I want to improve my understanding of expressions and I love being able to have strongly typed values instead of string literals it's so much nicer to work with.
Any thoughts, ideas, ramblings would be greatly appreciated
Cheers
Rob
发布评论
评论(2)
当您定义类似
Func
之类的内容时,意味着有一个方法采用 TModel 类型并返回 TProperty 类型。因此 lambda 表达式返回的是属性的值而不是属性本身。
要使此语法发挥作用,您可以按如下方式定义
ColumnProperty
:然后您可以从表达式树中提取详细信息。
When you define something like
Func<TModel, TProperty>
it means there is a method that takes a TModel type and returns a TProperty type. So lambda expressions likereturns the value of the property rather than the property itself.
What you can do to make this syntax work is to define your
ColumnProperty
as follows:Then you can extract detailed information from the expression tree.
好吧,我灵机一动,将 TProperty 更改为动态,我现在可以这样做,所以我想我回答了自己的问题,但很想了解其他人对这种方法的优点/缺点的想法:
事实上,
如果我更改我的属性我
只能这样做:
Ok so I just had a brainwave and changed TProperty to dynamic and I can now do this so I guess I answered my own question but would be keen on other peoples thoughts about the pros/cons of this approach:
In fact
if I change my property to
I can just do: