how to define custom generic convertor in c#
I want to make a converter class for myself where I want to declare a function to convert an object of one type to the other type.
For eg, if there are two classes -
class A
{
private int ID {get;set;}
private string Name {get;set;}
}
class B
{
private int ID {get;set;}
private string Name {get;set;}
private string Address {get;set;}
}
I have declared my class method like this -
T2 Convert<T1, T2>(T1 t1_object)
{
开发者_Go百科 A obj1 = (A)t1_object;
T2 obj2;
// ... some logic here where properties of t1_object are copied to obj2 (which will be of type B class)....
return obj2;
}
Any help will be great.
thanks!
You should have a look into AutoMapper
I upvoted devdigital's AutoMapper suggestion, but also wanted to suggest considering refactoring your classes to inherit from a base class, if possible. Thus your conversion/casting will be super simple.
I upvotet too on the AutoMapper solution, and a viable alternative is ValueInjecter, maybe a little simpler.
You can't create simple universal converter.
One way - Use reflection. You can convert objects automaticly. But it's not so simple. You'll have to write some code.
Another way - You can use very simple converter. But you have to describe convertion rules for every case. Commonly no need to write a lot of code for convertion. Here is example for your case
public static class ConvertExtension //exstension for convertion
{
//automatic convertion
//later you define in lambda wich data needs to be converted
public static T Convert<S, T>(this S source, Action<S, T> convert)
where S : class
where T : class
{
T target = System.Activator.CreateInstance<T>();
convert(source, target);
return target;
}
//convert data defined in interface
//you need copy all fields manually
public static T Convert<T>(this IData source)
where T : IData
{
T target = System.Activator.CreateInstance<T>();
target.ID = source.ID;
target.Name = source.Name;
return target;
}
}
public interface IData //Describe common properties
{
int ID {get; set;}
string Name {get; set;}
}
class A : IData //Interface already implemented. You just mark classes with interface
{
public int ID { get; set; }
public string Name { get; set; }
}
class B : IData
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
//example
A a = new A();
B b1 = a.Convert<B>();
B b2 = a.Convert<A, B>((s, t) => t.ID = s.ID);
精彩评论