So, Imagine you have a big object with more than 20 properties. Then you have an old object and a new object, how you can update for it? In normal way, we will set data for each property. So, new we have more than 20 object like this :)
A question, how we can write an function can update property data for T object?
Yes, we can. I found it. This post will you this function and how to use it on your project.
This function in this code snippet:
1: public static class Utils
2: {
3: public static void UpdateProperties<T>(T orginal, ref T dest, params string[] skips) where T : class
4: {
5: var destType = dest.GetType();
6: var destPropertyInfos = destType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
7: var orginalType = orginal.GetType();
8: var orginalPropertyInfos = orginalType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
9: foreach (var destInfo in destPropertyInfos)
10: {
11: var propertyName = destInfo.Name;
12: if (skips.Contains(propertyName)) continue;
13:
14: var orgInfo = GetValue(propertyName, orginalPropertyInfos);
15: destInfo.SetValue(dest, orgInfo.GetValue(orginal, null), null);
16: }
17: }
18:
19: private static PropertyInfo GetValue(string propertyName, IEnumerable<PropertyInfo> propertyInfos)
20: {
21: return propertyInfos.FirstOrDefault(info => info.Name == propertyName);
22: }
23: }
This functions will use type of object to get properties information, .NET support we can get and set value for a property. In loop, we will tranfer data from original object to destination object, but some properties you can skips tranfer, when you set names of them on skips parameter.
This is an demo to use it:
1: public class MyClass
2: {
3: public int Id { get; set; }
4: //with some properties
5: }
6:
7: static void Main()
8: {
9: // Original object with some new data
10: var fromObject = new MyClass();
11: // Destination object will be updated
12: var toObject = new MyClass();
13:
14: // Call update funtion
15: Utils.UpdateProperties(fromObject,ref toObject, null);
16: // Call update funtion with skip Id
17: Utils.UpdateProperties(fromObject, ref toObject, "Id");
18:
19: Console.ReadKey(true);
20: }
I have two objects of MyClass, I want to set data from fromObject to toObject. By call UpdateProperties function I can do it in short code.
It's really useful to me, so you are?
Thank to join it!
No comments:
Post a Comment