【发布时间】:2015-11-17 13:24:55
【问题描述】:
我编写了这些类来组成一个复合体,它可以包含泛型类型和值。
看起来没问题,但是当我想要合成时,我遇到了将合成中的 ISomething 转换为 Something 并获取其值的问题。 我不能将列表中的 ISomethings 转换为它们的类型,例如,转换为某些东西。
这里有什么技巧可以做,还是不能做?? (应该怎么做??) 谢谢 肯尼斯
public interface ISomething
{
string Name { get; set; }
}
public class Something<T> : ISomething
{
public string Name { get; set; }
public T Value { get; set; }
public Something(string name, T value)
{
Name = name;
Value = value;
}
}
public class CompositeSomething : Something<IList<ISomething>>
{
public CompositeSomething (string name)
: base(name, new List<ISomething>())
{
}
public void Add(ISomething newSomething)
{
Value.Add(newComponent);
}
public void Remove(ISomething oldSomething)
{
Value.Remove(oldSomething);
}
}
XmlNode BuildXml(Something something, XmlDocument document)
{
XmlNode node = document.CreateNode(XmlNodeType.Element,
something.Name, "");
foreach (ISomething item in compositeSomething.Value)
{
var isComposite = item is CompositeSomething;
if (isComposite)
{
node.AppendChild(BuildXml((CompositeSomething)item, document));
}
else
{
var child = (Something<T>)item; // FAILS!!!!
node.AppendChild(BuildXml(child,document));
}
}
return node;
}
【问题讨论】:
-
听起来您根本不想要
ISomething的列表 - 为什么不将CompositeSomething也设为通用,并带有Something<T>的列表? -
var child = (Something<T>)item;无论您的其他代码如何,都不会编译,因为您没有将它放在通用方法中;BuildXml不知道T是什么。如果你清楚地描述你想要达到的目标,你会得到更好的答案。 -
好点,我添加了
并编译,但调用它失败