Create an object from another object in C # using common code

Let's say I have a Type User object that looks like this:

User {
   Name = "Bob",
   Email = "Bob@gmail.com",
   Class = NULL
}

Can anyone think of a way to take this object and create such an object:

User {
   Name = "Bob",
   Email = "Bob@gmail.com"
}

Using fully shared code? Meaning, I do not want hard code to do anything with type or properties, because this code should apply to every object on my site. (the "User" type is an entity, by the way, use this if it helps you better do this).

I'm just trying to find a solution to the problem that I am facing, and I BELIEVE that Stub Entities can solve the problem, but I need to do this without hard coding any types or properties.

+3
source share
3

, :

public void CopyValues<TSource, TTarget>(TSource source, TTarget target)
{
    var sourceProperties = typeof(TSource).GetProperties().Where(p => p.CanRead);

    foreach (var property in sourceProperties)
    {
        var targetProperty = typeof(TTarget).GetProperty(property.Name);

        if (targetProperty != null && targetProperty.CanWrite && targetProperty.PropertyType.IsAssignableFrom(property.PropertyType))
        {
            var value = property.GetValue(source, null);

            targetProperty.SetValue(target, value, null);
        }
    }
}
+5

. Entity Framework - , .

Reflection. - :

public static void CopyProperties(object a, object b)
{
    if (a.GetType() != b.GetType())
        throw new ArgumentException("Types of object a and b should be the same", "b")

    foreach (PropertyInfo property in a.GetType().GetProperties())
    {
        if (!property.CanRead || !property.CanWrite || (property.GetIndexParameters().Length > 0))
            continue;

        property.SetValue(b, property.GetValue(a, null), null);
    }
}

, , , , getter. " " " ", , . , " "

+4

This looks like a problem for reflection, not for generics (although generics can be used as a hidden way to cache strategies for reflection). If I'm not mistaken, you want to create a new instance and copy most of the members ... Which reflection is good, albeit relatively slow. You can improve speed using metaprogramming; at the first start (for each type) it generates an optimized version, possibly using DynamicMethod or Expression and saving the dialed delegate from it. Then just use the delegate.

+2
source

All Articles