简体   繁体   中英

Why can't GetType().BaseClass find the base class?

Edit: its my fault as there was another Foo definition lurking around that made me confused with Foo<> definition.

In the below code, Foo is a base class of Bar right?

Then why compiler underlines the .BaseType part and says "the given expression is never of the provided (Form1.Foo) type"?

    // has 1 virtual method
    class Foo<T> : IList<T>
    {
        ...
    }

    // overrides 1 method from Foo
    class Bar : Foo<float>
    {

    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        object o = new Bar();


        if (o is Bar)
        {
            Console.WriteLine("2222222 "+ o.GetType().BaseType);
            if(o.GetType().BaseType is Foo)
            {
                Console.WriteLine("2.5 2.5 2.5 2.5 2.5");
            }
        }
        if (o is object)
            Console.WriteLine("3333333");
    }

output is:

2222222 VRAM.Form1+Foo`1[System.Single]
3333333

I'm trying to check if an object is assigned to an instance derived from Foo or not. Because in runtime, that object will be a primitive array or a Foo<float> or a Foo<int> or other T primitive types.

Also using typeof(Foo<>) for comparison doesn't work. I need only 1-depth checkş of wheter object o is derived from Foo<> or not. (I don't want to check all kinds like Bar Biz Baz that are integer double char types and many will be added later so I needed to check in 1line or 2 at most)

o.GetType().BaseType returns Type , not an instance you can check with is or as .

A better notation would be:

if(o.GetType().BaseType.GetGenericTypeDefinition() == typeof(Foo<>))

If you want to check equality of the type. Generally though it is better to use Type.IsAssignableFrom .

Code as given in the question will not compile unless you have a non-generic Foo lying around. In order to use typeof(Foo<>) , you should use the Type.GetGenericTypeDefinition MSDN - Type

if(o.GetType().BaseType is Foo){
    Console.WriteLine("2.5 2.5 2.5 2.5 2.5");
}

I need only 1-depth check of wheter object o is derived from Foo<> or not.

if(o.GetType().BaseType.GetGenericTypeDefinition() == typeof(Foo<>)){
    //STUFF
}

should work

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