我編寫了一個方法,它簡單地將一個對象的所有給定屬性復(fù)制到另一個具有相同類型的對象。這個方法是因為我不想手動定義當一個類有 100+ 時要復(fù)制的屬性(希望這永遠不會發(fā)生,但如果......)。 /// <summary> /// Copies the values of the given parameters from source to target /// Important Info: Works only with Properties, not with Fields /// </summary> /// <typeparam name="T">The Classtype</typeparam> /// <param name="target">The object the values are copied to</param> /// <param name="source">The object the values come from</param> /// <param name="properties">The Array containing the names of properties which shall be copied</param> private static void CopyParams<T>(T target, T source, params string[] properties) { foreach (var property in properties) { target.GetType().GetProperty(property)?.SetValue(target, source.GetType().GetProperty(property)?.GetValue(source)); } }但是因為這在循環(huán)內(nèi)使用反射,所以速度非常慢。對于 1.000.000 個對象和 2 個屬性,最多需要 2 秒。如果我手動執(zhí)行此操作,則需要 36 毫秒。有沒有辦法在性能上提高這一點?編輯 1正如一些人要求的對象的代碼,這里是:public class TestModel{ public string Name { get; set; } public int Value { get; set; } public void GetValues(TestModel m) { Name = m.Name; Value = m.Value; }}代碼是這樣調(diào)用的: private static void PerformanceTestReflection(int count) { var models = new List<TestModel>(); var copies = new List<TestModel>(); for (int i = 0; i < count; i++) { models.Add(new TestModel() { Name = "original", Value = 10 }); copies.Add(new TestModel() { Name = "copy", Value = 20 }); } Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { CopyParams(models[i], copies[i], nameof(TestModel.Name), nameof(TestModel.Value)); } Console.WriteLine($"Time for Reflection with {count} Models: {sw.ElapsedMilliseconds} ms - {sw.ElapsedTicks} ticks"); }
- 1 回答
- 0 關(guān)注
- 189 瀏覽
添加回答
舉報
0/150
提交
取消