【问题标题】:Get derived type class获取派生类型类
【发布时间】:2018-04-22 19:53:29
【问题描述】:

所以,我有以下结构:

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 个对象及更多

我在括号中给出了这个案例

如果有任何帮助,我将不胜感激

【问题讨论】:

  • 您能否更好地解释您想要实现的目标?
  • 您能解释一下您要达到的目标吗?你的例子根本不清楚。
  • 我在 A 之后继承了大约 100 个不同的对象。所以我需要在 A 类中找到派生类型(在这种情况下是 B 类)
  • System.Type 有一个'BaseType'-Property,你试过吗?您可以在 C-Instance 中调用 GetType().BaseType,这应该返回 B-Type
  • 我想过但是我在B之后继承了大约80个不同的对象,所以这种方式也很糟糕

标签: c#


【解决方案1】:

在对象的任何实例上,您都可以调用 .GetType() 来获取该对象的类型。

构造时不需要设置类型

【讨论】:

    【解决方案2】:

    我没有完全理解你的问题,但这些是获取有关类型信息的一些可能性:

    var a = new A();
    Console.WriteLine(a.GetType().Name); // Output: A
    Console.WriteLine(a.GetType().BaseType?.Name); // Output: MyBase
    
    var b = new B();
    Console.WriteLine(b.GetType().Name); // Output: B
    Console.WriteLine(b.GetType().BaseType?.Name); // Output: A
    
    // A simple loop to get to visit the derivance chain
    var currentType = b.GetType();
    while (currentType != typeof(object))
    {
        Console.WriteLine(currentType.Name);
        currentType = currentType.BaseType;
    }
    // Output: B A MyBase
    

    另外,我建议阅读this post 了解GetTypetypeof 之间的区别

    希望这会有所帮助。

    【讨论】:

    • 为了将您的答案扩展到我认为是 OP 问题的核心,请注意 B b = new B()A b = new B() 将产生与此答案中为 var b = new B() 列出的相同的输出。跨度>
    猜你喜欢
    • 2015-03-30
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    相关资源
    最近更新 更多