有没有一种方法可以使用Type变量而不是显式提供的类型来转换类的实例?可以通过Type变量而不是显式类型来转换类的实例吗?
例如在我的方法下面的“this”是派生类型的“Node”。我希望方法重复尝试从GetNodeIntrinsicProperty()获取一个值,之后如果它获得一个空值,它应该将其自身作为基本类型进行投射,然后重试。
基本上,我想调用GetNodeIntrinsicProperty()的每个实现,直到我得到一个值。
public string GetIntrinsicProperty(String propertyKey)
{
//sets the original type value
Type currType = this.GetType();
Node thisNode = this;
String propertyValue;
while (currType is Node)
{
//casts thisNode as CurrType
thisNode = thisNode as currType;
/*The live above gives me the following error
*
* Error 20 The type or namespace name 'currType' could not be found
(are you missing a using directive or an assembly reference?) */
//trys to get the property with the current cast
//GetNodeIntrinsicProperty() is defined seperately in each type
propertyValue = thisNode.GetNodeIntrinsicProperty(propertyKey);
if (propertyValue != null)
{
return propertyValue;
}
//sets CurrType to its base type
currType = currType.BaseType;
}
return null;
}
你能解释一下你为什么要这样做吗?有一个简单的方法可以确定你是否可以将某种类型转换为其他类型,所以看起来有点愚蠢,只是试图用暴力来实现。 – 2009-04-08 05:09:11
我很困惑。 GetNodeIntrinsicProperty是一个虚拟方法吗?如果是这样,为什么你需要改变类型? – 2009-04-08 05:24:05
同意安德鲁 - 使它虚拟,并使用多态。 – 2009-04-08 06:01:33