U
user
I want to get from ChildClass object an object of type BaseClass, how
can I do that ?
i need this conversion for existing code becouse a webService accepts
only BaseClass.
here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testDerivedBaseClass
{
public class BaseClass
{
public string s;
public int i;
public BaseClass()
{
;
}
}
public class ChildClass : BaseClass
{
public string child1;
public ChildClass()
{
}
}
class Program
{
static void Main(string[] args)
{
ChildClass C1 = new ChildClass();
BaseClass B1 = (BaseClass)C1;
string t = B1.GetType().ToString();
//t = "testDerivedBaseClass.ChildClass"
B1 = null;
B1 = C1 as BaseClass;
t = B1.GetType().ToString();
//t = "testDerivedBaseClass.ChildClass"
Console.Write(B1.i);
}
}
}
//////////////////////////////////////
I also made a function to copy object:
but i dont want to create copy filling memory.
/////////////////////////////////////
public static T1 CopyObject<T1, T2>(T2 obj)
where T1 : new()
{
T1 objNew = new T1();
Type classType = obj.GetType();
PropertyInfo[] arrProp = classType.GetProperties();
foreach (PropertyInfo p in arrProp)
{
if (p.CanWrite)
{
if ((objNew.GetType()).GetProperty(p.Name) != null)
{
p.SetValue(objNew, p.GetValue(obj, null), null);
}
}
}
return objNew;
}
can I do that ?
i need this conversion for existing code becouse a webService accepts
only BaseClass.
here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testDerivedBaseClass
{
public class BaseClass
{
public string s;
public int i;
public BaseClass()
{
;
}
}
public class ChildClass : BaseClass
{
public string child1;
public ChildClass()
{
}
}
class Program
{
static void Main(string[] args)
{
ChildClass C1 = new ChildClass();
BaseClass B1 = (BaseClass)C1;
string t = B1.GetType().ToString();
//t = "testDerivedBaseClass.ChildClass"
B1 = null;
B1 = C1 as BaseClass;
t = B1.GetType().ToString();
//t = "testDerivedBaseClass.ChildClass"
Console.Write(B1.i);
}
}
}
//////////////////////////////////////
I also made a function to copy object:
but i dont want to create copy filling memory.
/////////////////////////////////////
public static T1 CopyObject<T1, T2>(T2 obj)
where T1 : new()
{
T1 objNew = new T1();
Type classType = obj.GetType();
PropertyInfo[] arrProp = classType.GetProperties();
foreach (PropertyInfo p in arrProp)
{
if (p.CanWrite)
{
if ((objNew.GetType()).GetProperty(p.Name) != null)
{
p.SetValue(objNew, p.GetValue(obj, null), null);
}
}
}
return objNew;
}