我编写了一个方法,它简单地将一个对象的所有给定属性复制到另一个具有相同类型的对象。这个方法是因为我不想手动定义当一个类有 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");
}
相关分类