猿问

获取派生类型类

因此,我具有以下结构:


public abstract class MyBase

{

    public Type TargetType { get; protected set; }

}


public class A : MyBase

{

    public A()

    {

        TargetType = GetType();//Wrong, I need B class type not C

    }

}


public class B : A

{

    public B() { }

}


public class C : B

{

    public C() { }

}

当然,我可以通过这种方式接收我的类型:


public class B : A

{

    public B()

    {

        TargetType = typeof(B);

    }

}

实际上,我必须编写一些代码以使示例更清晰:


Class1.cs


public static Dictionary<Type, Type> MyTypes = new Dictionary<Type, Type>()

{

    { typeof(B),typeof(BView) }

}


public Class1()

{

    C itemC = new C();

    Class2.Initialize(itemC);

}

Class2.cs


public static Initialize(MyBase myBase)

{

    Type t;

    Class1.MyTypes.TryGetValue(myBase.TargetType, out t);

    //I need get BView but I get null because *myBase.TargetType* is C class type

}

等级结构:

  • 级别0:(MyBase)-1个对象

  • 级别1:(A)-2个对象

  • 2级:(B)-100个以上对象

  • 3级:(C)-80个对象及更多

我把这个案子放在括号里

我将不胜感激


拉丁的传说
浏览 127回答 2
2回答

喵喵时光机

在任何对象实例上,您可以调用.GetType()以获取该对象的类型。您不需要在建筑上设置类型
随时随地看视频慕课网APP
我要回答