【发布时间】: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#