![](/img/trans.png)
[英]How to make a Class with Generic types inherit from a non-generic class C#
[英]How to serialize a list of generic type which inherit from a non generic class
我有一個 class 結構如下:
[Serializable]
public abstract class TagConfiguration
{
public abstract string Name { get; set; }
// Other abstract properties
public abstract object GetInitialValue();
public abstract void SetInitialValue(object value);
protected TagConfiguration() { }
// Other methods not useful in the scope of this problem
}
[Serializable]
public class GenericTagConfiguration<T> : TagConfiguration
{
public override string Name { get; set; }
// Other abstract properties
private T _initialValue;
public T InitialValue
{
get => (T)GetInitialValue();
set => SetInitialValue(value);
}
public override object GetInitialValue()
{
return _initialValue;
}
public override void SetInitialValue(object value)
{
_initialValue = (T)value;
}
public GenericTagConfiguration() : base() { }
// Other methods not useful in the scope of this problem
}
這個 class,顧名思義是用於配置一個標簽 object,如下所示:
[Serializable]
public abstract class Tag
{
public abstract object GetConfiguration();
public abstract void SetConfiguration(object value);
public abstract object GetCurrentValue();
public abstract void SetCurrentValue(object value);
protected Tag() { }
// Some abstract methods
}
[Serializable]
public class GenericTag<T> : Tag
{
private GenericTagConfiguration<T> _configuration;
public TagConfiguration Configuration
{
get => (GenericTagConfiguration<T>)GetConfiguration();
set => SetConfiguration(value);
}
public override object GetConfiguration()
{
return _configuration;
}
public override void SetConfiguration(object value)
{
_configuration = (GenericTagConfiguration<T>)value;
}
private T _currentValue;
public T CurrentValue
{
get => (T)GetCurrentValue();
set => SetCurrentValue(value);
}
public override object GetCurrentValue()
{
return _currentValue;
}
public override void SetCurrentValue(object value)
{
_currentValue = (T)value;
}
public GenericTag() : base() { }
// The same methods from Tag overridden
}
我必須能夠將List<TagConfiguration>
導出到 XML 文件,但我遇到的問題是每當我嘗試這樣做時,都會收到一條錯誤消息:
Unhandled Exception: System.InvalidOperationException: There was an error generating the XML document.
---> System.InvalidOperationException:The type GenericTagConfiguration[[System.Int32]] was not expected.
Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
我正在使用以下代碼嘗試導出:
List<TagConfiguration> lstTagConf = new List<TagConfiguration>
{
tagConf,
tagConf2
};
XmlSerializer xs = new XmlSerializer(typeof(List<TagConfiguration>));
using (TextWriter tw = new StreamWriter(@"C:\Users\Administrator\Documents\listTag.xml"))
{
xs.Serialize(tw, lstTagConf);
}
問題
我添加Tag
class 的原因是我需要能夠導入和導出List<Tag>
以及List<TagConfiguration>
。
我需要編寫一個接口來執行此操作嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.