tailieunhanh - Effective C#50 Specific Ways to Improve Your C# Second Edition phần 9

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 where 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 where destProp null 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 dest destProp 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 dest typeof TDest assignments dest Finally it s time to build a lambda that returns the destination object and contains all the statements built so far var expr Func TSource TDest new dest expression parameters 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 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Ừ KHÓA LIÊN QUAN