开发者

passing values between 2 classes by casting

I have

public class MyClass1
{
   public string Name;
   public string Address;
}
public class MyClass2
{
   public int Id; 
   public strin开发者_如何学编程g Name;
   public string Address;
}

var a = new MyClass1 {Name="SomeName", Address="SomeAddress" };

I dont want to do

b.Name = a.Name;
b.Address = a.Address 

because I have more than 30 fields.

I want is:

MyClass2 b = a;


What you want is not possible. I would recommend you AutoMapper which allows you to define a mapping:

Mapper.CreateMap<MyClass1, MyClass2>();

and then map between instances of those two classes:

var a = new MyClass1 { Name = "SomeName", Address = "SomeAddress" };
var b = Mapper.Map<MyClass1, MyClass2>(a);

As a bonus you will be able to do the following:

IEnumerable<MyClass1> list1 = ...
IEnumerable<MyClass2> list2 = Mapper.Map<IEnumerable<MyClass1>, IEnumerable<MyClass2>>(list1);

Another possibility is to use reflection to loop through all properties of the source object and set them in the target object but why reinventing wheels when such great tools like AutoMapper exist?


Its better you use reflection as it can loop all the properties and can set the value of matching attributes

http://odetocode.com/articles/288.aspx

check how it is retrieving values from properties

 PropertyInfo[] properties = type.GetProperties();

 foreach(PropertyInfo property in properties)
 {
 }


As an alternate solution you could create a constructor in MyClass2 that takes an instance of MyClass1 and sets all the properties.

public class MyClass2
{
    public int Id; 
    public string Name;
    public string Address;

    public MyClass2(MyClass1 a)
    {
        this.Name = a.Name;
        this.Address = a.Address;
    }
}

Then you could do this

MyClass2 b = new MyClass2(a);


The simplest thing to do is simply have a method called updateFromClass1(MyClass1) in MyClass2

You can also use Reflection . Use http://msdn.microsoft.com/en-us/library/ch9714z3.aspx to get all the fields from a type. FieldInfo has get and set methods to update the value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜