简体   繁体   中英

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));
            }
        }

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 .

您可以使用反射和泛型来将名称相同的属性相互映射,但是我认为您不能在不克隆或实例化新对象的情况下更改对象的基本类型。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM