Which is equivalent to Javascript Object.assign () in C #

If I have a C # class

public class Foo
{
    public int? a { get; set; }
    public int? b { get; set; }
}

And two instances of this class

var foo1 = new Foo() { a = 1 };
var foo2 = new Foo() { b = 1 };

How can I copy values ​​from both objects to create a new instance Foocontaining values ​​from foo1both and foo2?

In Javascript, it will be as simple as

var foo3 = Object.assign({}, foo1, foo2);
+4
source share
3 answers

You can create a method that combines objects through reflection. But be careful, this is slow, usually cannot be used in C #.

Care should be taken to skip "empty" properties. In your case, these are value types. In my example implementation, each property is skipped if its default value is of this type (for int it is 0):

public T CreateFromObjects<T>(params T[] sources)
    where T : new()
{
    var ret = new T();
    MergeObjects(ret, sources);

    return ret;
}

public void MergeObjects<T>(T target, params T[] sources)
{
    Func<PropertyInfo, T, bool> predicate = (p, s) =>
    {
        if (p.GetValue(s).Equals(GetDefault(p.PropertyType)))
        {
            return false;
        }

        return true;
    };

    MergeObjects(target, predicate, sources);
}

public void MergeObjects<T>(T target, Func<PropertyInfo, T, bool> predicate, params T[] sources)
{
    foreach (var propertyInfo in typeof(T).GetProperties().Where(prop => prop.CanRead && prop.CanWrite))
    {
        foreach (var source in sources)
        {
            if (predicate(propertyInfo, source))
            {
                propertyInfo.SetValue(target, propertyInfo.GetValue(source));
            }
        }
    }
}

private static object GetDefault(Type type)
{
    if (type.IsValueType)
    {
        return Activator.CreateInstance(type);
    }
    return null;
}

using:

var foo3 = CreateFromObjects(foo1, foo2);
+3

, .

var foo3 = new Foo() {a = foo1.a, b = foo2.b };
+1

Vivek . Object.Assign . javascript, Object.Assign, # , . .

Javascript , . , () .

, :

0

Source: https://habr.com/ru/post/1659726/


All Articles