Đang chuẩn bị liên kết để tải về tài liệu:
Effective C#50 Specific Ways to Improve Your C# Second Edition phần 9

Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ

Chúng ta hãy khai báo một biến địa phương giữ tài sản cùng tên trong các loại đích. Nó có thể là null, nếu các loại điểm đến không có một tài sản của các loại chính xác:Theo dự báo của các truy vấn là một chuỗi các báo cáo phân giao tài sản của đối tượng đích với giá trị của cùng một tên thuộc tính trong đối tượng nguồn: | 260 I Chapter 5 Dynamic Programming in C from srcProp in typeof TSource .GetProperties BindingFlags.Public BindingFlags.Instance where srcProp.CanRead The let declares a local variable that holds the property of the same name in the destination type. It may be null if the destination type does not have a property of the correct type let destProp typeof TDest .GetProperty srcProp.Name BindingFlags.Public BindingFlags.Instance where destProp null destProp.CanWrite The projection of the query is a sequence of assignment statements that assigns the property of the destination object to the value of the same property name in the source object select Expression.Assign Expression.Property dest destProp Expression.Property source srcProp The rest of the method builds the body of the lambda expression. The Block method of the Expression class needs all the statements in an array of Expression. The next step is to create a List Expression where you can add all the statements. The list can be easily converted to an array. var body new List Expression body.Add Expression.Assign dest Expression.New typeof TDest body.AddRange assignments body.Add dest Finally it s time to build a lambda that returns the destination object and contains all the statements built so far var expr Expression.Lambda Func TSource TDest Expression.Block new dest expression parameters body.ToArray body source lambda expression From the Library of Wow eBook Item 43 Use Expressions to Transform Late Binding into Early Binding I 261 That s all the code you need. Time to compile it and turn it into a delegate that you can call var func expr.Compile converter func That is complicated and it s not the easiest to write. You ll often find compiler-like errors at runtime until you get the expressions built correctly. It s also clearly not the best way to approach simple problems. But even so the Expression APIs are much simpler than their predecessors in the Reflection APIs. That s when you should use the .

TÀI LIỆU LIÊN QUAN