【发布时间】:2010-05-03 23:57:07
【问题描述】:
好的,所以我目前正在使用一组类,我无法在使用这些对象的一些非常通用的函数中控制这些类。我决定改用一个泛型函数,而不是写几十个对每个类基本上做同样事情的函数。
现在我正在处理的类有点奇怪,因为派生类共享许多相同的属性,但派生它们的基类却没有。一个这样的属性示例是 .Parent,它存在于大量派生类中,但不存在于基类中,我需要使用此属性。
为了便于理解,我创建了一个小示例,如下所示:
class StandardBaseClass {} // These are simulating the SMO objects
class StandardDerivedClass : StandardBaseClass {
public object Parent { get; set; }
}
static class Extensions
{
public static object GetParent(this StandardDerivedClass sdc) {
return sdc.Parent;
}
public static object GetParent(this StandardBaseClass sbc)
{
throw new NotImplementedException("StandardBaseClass does not contain a property Parent");
}
// This is the Generic function I'm trying to write and need the Parent property.
public static void DoSomething<T>(T foo) where T : StandardBaseClass
{
object Parent = ((T)foo).GetParent();
}
}
在上面的示例中,调用 DoSomething() 将在 GetParent() 的基类实现中抛出 NotImplemented 异常,即使我强制转换为 StandardDerivedClass 的 T。
这与其他强制转换行为相反,通过向下转换将强制使用基类的实现。
我将此行为视为错误。有没有其他人遇到过这种情况?
【问题讨论】:
-
你说“我强制转换为 T 这是一个 StandardDerivedClass”,但代码显示“where T : StandardBaseClass”
标签: c# generics inheritance polymorphism