开发者

c# Type conversion between unrelated objects

We are in the progress of migrating Data Access Layers to a newer, more supported, and more generated DAL than the currently used one.

As such, we have many different object that while are technically different, represent collections of data that can be easily transferred/converted to each other without data loss.

What's the most flexible, or most widely used, or most preferred, etc me开发者_JS百科thodology to perform this type of type conversion?

i'm considering writing a set of partial classes that implement IConvertible. i've also considered creating a System.ComponentModel.TypeConverter to perform the conversions. Are there any other options that may be better at this that I may have not considered?

What options are available?

ideally, i'd like to keep these conversions in an extension class or different library as to not clutter up our project references. The clutter can live in this one special conversion library.

For instance,

in DAL1.DataTypes i have a class Table1Data

in DAL2.DataTypes i have a class Table1

Thanks.


You can use an automated mapper - look at automapper:

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values.


BLToolkit supports pretty performant low-effort object mapping: http://bltoolkit.net/Doc.ObjectToObject.ashx

public class SourceObject
{
    public bool   Value1   = true;
    public string Value2   = "10";
    public string StrValue = "test";
}

public class DestObject
{
    [MapField("Value1")] public bool   BoolValue;
    [MapField("Value2")] public int    IntValue;

    // If source and destination field or property names are equal,
    // there is no need to use MapField attribute.
    //
    public string StrValue; 
}

public void Test()
{
    SourceObject source = new SourceObject();
    DestObject   dest   = Map.ObjectToObject<DestObject>(source);
}

Upd: with recent SO update it's a real pain to use code snippets in IE6, sorry if there are any code formatting issues.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜