How do I populate current class with new class values?

This one is a little difficult to explain so I'll show code first..

Note: Made example less confusing

public class Class1
{
     public string Title {get;set;}
     public string Name {get;set;}


     public Class1(Class1 class1)
     {
         // ?? How do I populate current class with new class values?
         // ?? this = class1;  - Does not work
         // I want to avoid having to manually set each value
     }
}

Thanks for help.. here what I did.. Created this in my extension class.. so I can now do

Extensions.MapValues(class1, this);

    public static void MapValues(object from, object to)
    {
        var fromProperties = from.GetType().GetProperties();
        var toProperties = to.GetType().GetProperties();

        foreach (var property in toProperties) {
            var fromProp = fromProperties.SingleOrDefault(x => x.Name.ToLower() == property.Name.ToLower());

            if(fromProp == null) {
                continue;
            }

            var fromValue = fromProp.GetValue(from, null);
            if(fromValue == null) {
                continue;
            }

            property.SetValue(to, fromValue, null);
        }
    }



It'll probably be easier to manually set each value.

That said, if the column name of the DataRow is the same for each property in your class, and if the types are equally the same, you could use Reflection to set the property name. You would do it somewhat like this:

public Class1(DataRow row)
{
    var type = typeof(Class1);
    foreach(var col in row.Table.Columns)
    {
        var property = type.GetProperty(col.ColumnName);
        property.SetValue(this, row.Item(col), null);
    }
}

You can't.

You can either manually copy over the properties, or replace the constructor with a static factory method that returns row.ToClass1() .

链接地址: http://www.djcxy.com/p/53780.html

上一篇: 基于动态加载的插件

下一篇: 如何用新的类值填充当前类?