How can I get an instance of a base class from an inherited class dynamically?
I'开发者_运维知识库ve got a class public class foubar : fou
fou has its properties and so does foubar I've created an instance of foubar and set values to all the properties including the base classes'. Now I need an instance of fou that has the property values that are in foubar. True, I could create a new instance of fou and write code that would populate this new instance from a foubar instance but that means I have to change to code every time the base class properties change.
I'd like something that would work like this, where FB is an instance of foubar
fou test = (fou) FB;
This "works" in C#, but test is really type foubar. I need only fou, nothing else,
I want a way to dynamically return an instance of a base class populated from the data/instance of the derived class.
Ideas?
I used reflection to dynamically make a copy of the base class' fields. Got this from: C# Using Reflection to copy base class properties Now I have a true fou type I can pass to EF.
private fou GetBaseData(foubar FB)
{
fou test_fou = new fou();
Type type = FB.GetType();
type = type.BaseType;
UpdateForType(type, FB, test_fou);
return test_fou;
}
private static void UpdateForType(Type type, foubar source, fou destination)
{
FieldInfo[] myObjectFields = type.GetFields(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo fi in myObjectFields)
{
fi.SetValue(destination, fi.GetValue(source));
}
}
You could use reflection and generics to map like-named properties to eachother, but I don't think you can change the base type of an object without cloning or instantiating a new one.
I don't see why do you need such a thing? But you can do something like this:
class Foo
{
// ...
public Foo ConcreteFoo()
{
if (this.GetType().Equals(typeof(Foo)))
return this;
else
{
Foo f = new Foo();
// clone properties
return f;
}
}
}
So you can do:
FouBar foobar = new FooBar();
Foo f = foobar.ConcreteFoo();
I'm really not comfortable with this ... Is there any special reason why you want a concrete Foo
?
(edit)
Following the comments I can see that your problem is related to this question.
精彩评论