DataContractSerializer的抽象(基地)/混凝土(继承)班混凝土、抽象、基地、DataContractSerializer

由网友(明月本无心)分享简介:鉴于这种code public override void Serialize(BaseContentObject obj){string file = ObjectDataStoreFolder + obj.Slug + ".xml";if(obj.GetType() == typeof(Page)){DataC...

鉴于这种code

public override void Serialize(BaseContentObject obj)
{
    string file = ObjectDataStoreFolder + obj.Slug + ".xml";
    if(obj.GetType() == typeof(Page))
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof Page));
        XmlDictionaryWriter myWriter =
            XmlDictionaryWriter.CreateTextWriter(new FileStream(file, ileMode.CreateNew, FileAccess.Write),
                                             Encoding.UTF8);
        dcs.WriteObject(myWriter, obj);
        myWriter.Close();
    }
    else if(obj.GetType() == typeof(Image))
    {
        DataContractSerializer dcs = new DataContractSerializer(typeof Image));
        ...
        ...
    }
}

有没有办法做这样的事情

is there a way to do something like this

DataContractSerializer dcs = new DataContractSerializer(obj.GetType());
// this fails however, compiler error

和摆脱那些如果()上面的语句?的DataContractSerializer的构造函数有期望类型或命名空间,但它不与obj.GetType()工作。

and get rid of those if() statements above? The constructor of DataContractSerializer there expects Type or Namespace but it does not work with obj.GetType().

我的类层次结构如下:

BaseContentClass(摘要)

BaseContentClass (abstract)

页(混凝土,继承BaseContentClass)

Page (concrete, inherits BaseContentClass)

图片(混凝土,继承BaseContentClass)

Image (concrete, inherits BaseContentClass)

...

推荐答案

如果你正在谈论这个的的DataContractSerializer 的那么下面code编译罚款:

If you are talking about this DataContractSerializer then the following code will compile fine:

DataContractSerializer dcs = new DataContractSerializer(obj.GetType());

由于构造函数需要一个类型参数。

As the constructor expects a type parameter.

阅读全文

相关推荐

最新文章