亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# - 如何使用反射改進代碼

C# - 如何使用反射改進代碼

C#
繁星點點滴滴 2021-10-31 19:09:43
我編寫了一個方法,它簡單地將一個對象的所有給定屬性復制到另一個具有相同類型的對象。這個方法是因為我不想手動定義當一個類有 100+ 時要復制的屬性(希望這永遠不會發生,但如果......)。    /// <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));        }    }但是因為這在循環內使用反射,所以速度非常慢。對于 1.000.000 個對象和 2 個屬性,最多需要 2 秒。如果我手動執行此操作,則需要 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;    }}代碼是這樣調用的:    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 回答

  • 1 回答
  • 0 關注
  • 193 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號