【发布时间】:2014-05-27 03:14:50
【问题描述】:
我认为这可能是不可能的,但如果是这样就会知道。
我有一个静态维护其子类实例的抽象类。我想在我的基类中实现一个静态getInstance() 方法,该方法将获取引用的任何类的实例。所以我需要一种方法来判断静态调用中引用了哪个类。
我认为代码会更清楚地说明这一点:
abstract class Base
{
private static List<Base> allInstances;
public static List<Base> AllInstances
{
get {
if(allInstances==null)
{
// Implementation not relevant and not included to avoid clutter
}
return allInstances;
}
}
public static Base getInstance()
{
Type callingType = // This is what I am trying to fill in
if(callingType == typeof(Base))
throw new InvalidOperationException("Cannot get instance of Base class");
return AllInstances.Find(i => i.GetType() == callingType);
}
}
class A:Base { }
class B:Base { }
所以如果我调用A.getInstance() 我的callingType 变量将是typeof(A)。我的主要目标是避免在我的代码中调用 Find 以使其更清晰、更具可读性,但我也很好奇这是否可能。
【问题讨论】:
-
你的意思是
getInstance是静态的吗?您正在谈论它,就像它是静态的一样。如果没有,请使用this.GetType()。 -
@mikez 我做到了。我重写了这个以显示我在说什么,而不是使用我的实际代码,并且没有足够仔细地校对它。我已经修好了。
-
我明白了。您不能不将某些内容放入所有派生类中。这是因为虽然您可以使用
A.getInstance和B.getInstance调用该方法,但它会编译为Base.getInstance。 -
@mikez 我怀疑这可能是编译器会如何处理它,但不确定。如果您将其发布为答案,我会标记它。
-
您可以做一个非常骇人听闻的技巧并使用
callingType = new StackTrace().GetFrame(1).GetMethod().ReflectedType;这将获取调用者的堆栈帧,然后提取调用类型。另见msdn.microsoft.com/en-us/library/…