我正在针对.NET 4.0构建以下类:
public class ConfigurationElementCollection<TElement, TParent>
where TElement : ParentedConfigElement<TParent>, new()
where TParent : class
{
public TParent ParentElement { get; set; }
protected ConfigurationElement CreateNewElement()
{
//**************************************************
//COMPILER GIVES TYPE CONVERSION ERROR ON THIS LINE!
//**************************************************
return new TElement { ParentCollection = this };
}
}
public class ParentedConfigElement<TParent> : ConfigurationElement where TParent : class
{
internal ConfigurationElementCollection<ParentedConfigElement<TParent>, TParent>
ParentCollection { get; set; }
protected TParent Parent
{
get
{
return ParentCollection != null ? ParentCollection.ParentElement : null;
}
}
}
正如上面的代码注释所指示的那样,编译器会给出一个错误信息:
“无法将类型'Shared.Configuration.ConfigurationElementCollection'隐式转换为类型'Shared.Configuration.ConfigurationElementCollection'”
我并不希望出现这个错误,因为编译器也知道由于我指定了泛型类型约束条件,
TElement
是一个 Shared.Configuration.ParentedConfigElement<TParent>
。尽管如此,我认为我仍需要显式地进行类型转换,以克服这个问题。
(ConfigurationElementCollection<ParentedConfigElement<TParent>,TParent>) this;
不幸的是,我得到了相同的编译器错误。为什么会发生这种情况?我做错了什么?而且在不使用 dynamic
类型的情况下,我该怎么做才能解决这个问题?