你好,这是我的第一篇帖子,如果我做错了什么,请不要过于苛刻:D
我正在为一个大程序员写一个DeSerializer,为此,我有一个自己的类
public class DeSerializeableElement
{
public Func<Object> action;
public Type type;
public DeSerializeableElement( Func<Object> p_action,Type p_type)
{
type = p_type;
action = p_action;
}我读一个字符串,然后它总是以0XXX开始,一个4位的数字。有了这个数字,我从我的
Dictionary<int,DeSerializableElement>字典的初始化是自动生成的,有300个元素
deSerializableObjectDictionary.Add(276, new DeSerializeableElement(GetString, typeof(System.String)));GetString是一个不带参数的方法,它返回一个字符串
现在我的问题是,如果我反序列化一个列表,在我创建一个DeSerializableElement的时候,函数会丢失它的返回值信息。因为我将它保存为Func,所以我会得到一个列表,但是在GetString的情况下获得一个列表是很重要的,还有GetInt或GetDouble等等
因此,如果我调用GetList(GetString),我想要一个列表作为返回值,如果我调用GetList(GetInt),我想要一个列表,依此类推。但是我总是得到一个列表,因为我的SerializableElement有Func as属性
对GetList的调用如下所示
GetList(deSerializableObjectDictionary[objectIdent].action);GetList看起来像
public IList<T> GetList<T>(Func<T> p_action) //T is always Object because of Func<Object> here I the right Type
{
IList<T> list = new List<T>();
ExpectToken('['); //The start Token of a serialized List
while (!IsNextToken(']')) //End Token of serialized List
{
list.Add(p_action());
}
return lst;
}发布于 2016-03-16 16:09:38
无论你选择哪条路,它都会使你失去类型安全。例如,您可以遵从Dictionary<int, object>并将其包装在GetList<T>方法中,其中T是您想要的实际类型。此方法的误用可能会导致运行时异常。
下面是一个例子:
void Main()
{
var idToFunc = new Dictionary<int, object>();
idToFunc.Add(1, new DeSerializeableElement<int>(() => 1));
Console.WriteLine(GetList<int>(((DeSerializeableElement<int>) idToFunc[1]).Func));
}
public class DeSerializeableElement<T>
{
public Func<T> Func { get; set; }
public DeSerializeableElement(Func<T> func)
{
Func = func;
}
}我肯定会考虑到这种代码所涉及的风险。尽管有可能,我还是建议你重新考虑你正在做的事情和你的反序列化程序的架构。
https://stackoverflow.com/questions/36029717
复制相似问题