开发者

Copy properties from class A to class B

开发者 https://www.devze.com 2023-02-02 12:34 出处:网络
Using C#, is there a way to copy properies from Class A that were set ( so if i didnt set some property in Class A I dont want that to get copied over) to class B?

Using C#, is there a way to copy properies from Class A that were set ( so if i didnt set some property in Class A I dont want that to get copied over) to class B?

example:

class A
{public string Name {get;set;}
public string Age {get;set;}
}

class B
{public string Name {get;set;}
public string Age {get;set;}
}


A a = new A(){name ="bob"}

Now i have B b = new B(){Age = 30}; I need to copy A to B that way Name of B gets set and 开发者_Python百科Age stays the same. Thanks


http://automapper.codeplex.com/


Well, you could do something like:

if (b.Name == null) b.Name = a.Name;
if (b.Age == null) b.Age = a.Age;

But this won't work for value types (like Int32). For those, if you control the definition of the type, you could use Nullable<T>.

0

精彩评论

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

关注公众号