gpt4 book ai didi

c# - 类型约束 C# 泛型的无效转换

转载 作者:太空狗 更新时间:2023-10-29 20:23:37 26 4
gpt4 key购买 nike

针对 .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;
}
}
}

如上代码注释所示,编译器报错:

Cannot implicitly convert type 'Shared.Configuration.ConfigurationElementCollection<TElement, TParent>' to 'Shared.Configuration.ConfigurationElementCollection<Shared.Configuration.ParentedConfigElement,TParent>

我不希望出现这个错误,因为编译器也知道 TElementShared.Configuration.ParentedConfigElement<TParent>由于我指定的通用类型约束。

不过,我想我会明确地转换类型来解决这个问题:

(ConfigurationElementCollection<ParentedConfigElement<TParent>,TParent>) this;

不幸的是,我遇到了同样的编译器错误。为什么会这样?我做错什么了?并且不求助于dynamic类型,我该怎么做才能解决这个问题?

最佳答案

基于 https://stackoverflow.com/a/6529618/5071902

protected ConfigurationElement CreateNewElement()
{
return (TElement)Activator.CreateInstance(typeof(TElement), this);
}

You will need a constructor with this signature, setting the ParentCollection property.

您也可以尝试使用反射。看看这个答案https://stackoverflow.com/a/6529622/5071902

关于c# - 类型约束 C# 泛型的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32514439/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com