第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

C#
繁星點點滴滴 2021-10-31 19:09:43
我編寫了一個方法,它簡單地將一個對象的所有給定屬性復(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 回答

  • 1 回答
  • 0 關(guān)注
  • 189 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號