I'm working in c# with several workspaces that have one specific class which his always the same in each workspace. I would like to be able have a copy of this class to be able to work with it without dealing with namespaces differences. example :
namespace1 {
class class1{
public class2;
}
class class2{
public string;
}
}
namespace2 {
class class1{
public class2;
}
class class2{
public string;
}
}
In my copied Class I've got a function to copy all data's to one of the namespace's class. It's working if i only have c# standard types. I got exeption ( "Object does not match target type." ) as soon as I'm dealing with class2 object (which is also from different namespaces)
public Object toNamespaceClass(Object namespaceClass)
{
try
{
Type fromType = this.GetType();
Type toType = namespaceClass.GetType();
PropertyInfo[] fromProps = fromType.GetProperties();
PropertyInfo[] toProps = toType.GetProperties();
for (int i = 0; i < fromProps.Length; i++)
{
PropertyInfo fromProp = fromProps[i];
PropertyInfo toProp = toType.GetProperty(fromProp.Name);
if (toProp != null)
{
toProp.SetValue(this, fromProp.GetValue(namespaceClass, null), null);
}
}
}
catch (Exception ex)
{
}
return namespaceClass;
}
Anyone do have any idea of how to deal with this kind of "recursivity reflection".
I hope eveything is understandable.
Thanks, Bye!
Edit : I think i got it solved (at least in my mind), I'll try the solution back at work tomorrow. Taking my function out of my class and using it recursively if a property is not a standard type is maybe the solution.
I had the similar problem. I got to use similar classes but different in terms of namespace only. As a quick solution I performed below steps and it works.
I know there is performance overhead with above way but it is quick to implement and error free.
You either need to refactor all of your duplicate classes into a single shared class or implement a common interface that all of your various classes implement. If you really can't modify the underlying types, create a subclass for each that implements your common interface.
Yes, you can do it with reflection... but you really shouldn't because you end up with brittle, error prone, code.
from here
Two identical or similar objects from different namespaces ?
You have this:
Time to apply some class inheritance:
And to copy, there is a copy method or constructor, but, I prefer a custom one:
Cheers.
BinaryFormatter does not work in .Net 4.5 as it remembers from what type of class the instance was created. But with JSON format, it does not. JSON serializer is implemented by Microsoft in DataContractJosnSerializer.
This works:
and uses as follows:
I got it solved , just to let you know how I did it : This solution is sot perfect because it handle only 1 dimensions array not more.
Hope this can help some people. Thanks for helping everyone. Cheers