DataContract“Type”属性的序列化

时间:2011-09-20 16:26:32

标签: c# .net serialization datacontract

如何在DataContract属性类中有效地序列化“Type”类型的属性?我假设Type是一个不可序列化的类型(哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇哇。基本上我需要为工厂方法序列化类型的名称以便有效地构造,但是我不想将它作为字符串公开,我想要一个Type。

我知道有很多方法可以做到这一点,我很好奇目前还知道其他什么方法。

编辑: 我刚刚意识到它可能是导致它的其他东西,但这里是错误,下面我有类定义。

不期望输入数据合约名称为“RuntimeType:http://schemas.datacontract.org/2004/07/System”的“System.RuntimeType”。考虑使用DataContractResolver或将任何静态未知的类型添加到已知类型列表中 - 例如,使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。

[DataContract]
public class PlottingDeviceInfo : ObservableObject
{
    private string _deviceName;
    [DataMember]
    public string DeviceName
    {
        get
        {
            return _deviceName;
        }
        set
        {
            Set(() => DeviceName, ref _deviceName, value);
        }
    }

    private Type _deviceType;
    [DataMember]
    public Type DeviceType
    {
        get
        {
            return _deviceType;
        }
        set
        {
            Set(() => DeviceType, ref _deviceType, value);
        }
    }

    private DeviceSettingsInfo _settings;
    [DataMember]
    public DeviceSettingsInfo Settings
    {
        get
        {
            return _settings;
        }
        set
        {
            Set(() => Settings, ref _settings, value);
        }
    }

    private DeviceChannelInfo _channel;
    [DataMember]
    public DeviceChannelInfo Channel
    {
        get
        {
            return _channel;
        }
        set
        {
            Set(() => Channel, ref _channel, value);
        }
    }

    private DeviceCategory _deviceCategory;
    [IgnoreDataMember]
    public DeviceCategory DeviceCategory
    {
        get
        {
            return _deviceCategory;
        }
        set
        {
            Set(() => DeviceCategory, ref _deviceCategory, value);
        }
    }
}

这是基类,用于为viewmodel消费添加可观察性。

[DataContract]
public class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    [IgnoreDataMember]
    protected PropertyChangedEventHandler PropertyChangedHandler
    {
        get
        {
            return PropertyChanged;
        }
    }

    [Conditional("DEBUG")]
    [DebuggerStepThrough]
    public void VerifyPropertyName(string propertyName)
    {
        var myType = this.GetType();
        if (!string.IsNullOrEmpty(propertyName)
            && myType.GetProperty(propertyName) == null)
        {
            throw new ArgumentException("Property not found", propertyName);
        }
    }

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        VerifyPropertyName(propertyName);

        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
    {
        if (propertyExpression == null)
        {
            return;
        }

        var handler = PropertyChanged;

        if (handler != null)
        {
            var body = propertyExpression.Body as MemberExpression;
            handler(this, new PropertyChangedEventArgs(body.Member.Name));
        }
    }

    protected void Set<T>(
        Expression<Func<T>> propertyExpression,
        ref T field,
        T newValue)
    {
        if (EqualityComparer<T>.Default.Equals(field, newValue))
        {
            return;
        }

        field = newValue;
        RaisePropertyChanged(propertyExpression);
    }

    protected void Set<T>(
        string propertyName,
        ref T field,
        T newValue)
    {
        if (EqualityComparer<T>.Default.Equals(field, newValue))
        {
            return;
        }

        field = newValue;
        RaisePropertyChanged(propertyName);
    }
}

3 个答案:

答案 0 :(得分:10)

Type无法以跨平台方式表达,因此它没有内置表示。你最好的选择是把它表示为一个字符串,即

public Type DeviceType { get; set; }
[DataMember(Name="DeviceType")]
private string DeviceTypeName {
    get { return DeviceType == null ? null : DeviceType.AssemblyQualifiedName; }
    set { DeviceType = value == null ? null : Type.GetType(value); }
}

答案 1 :(得分:0)

向根类添加KnownType属性,并将System.RuntimeType作为类型传入。{/ p>

在C#中,

[KnownType(typeof(System.RuntimeType))]

答案 2 :(得分:0)

您还可以执行的操作(尤其是在您不想更改PlottingDeviceInfo时)是在IDataContractSurrogate的构造函数中传递DataContractSerializer。我所做的(不知道是否有更简单的方法)是定义

public class TypeWrapper
{
    public string TypeName;
}

然后像这样使用它:

public class TypeReplacementSurrogate : IDataContractSurrogate
{
    public object GetCustomDataToExport(Type clrType, Type dataContractType)
    {
        return null;
    }

    public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
    {
        return null;
    }

    public Type GetDataContractType(Type type)
    {
        if(type == typeof(Type))
        {
            return typeof (TypeWrapper);
        }

        return type;
    }

    public object GetDeserializedObject(object obj, Type targetType)
    {
        var objAsTypeWrapper = obj as TypeWrapper;
        if (objAsTypeWrapper != null)
        {
            return Assembly.GetExecutingAssembly().GetType(objAsTypeWrapper.TypeName);
        }

        return obj;
    }


    public void GetKnownCustomDataTypes(System.Collections.ObjectModel.Collection<Type> customDataTypes)
    {
    }

    public object GetObjectToSerialize(object obj, Type targetType)
    {
        var objAsType = obj as Type;
        if (objAsType != null)
        {
            return new TypeWrapper() {TypeName = objAsType.FullName};
        }

        return obj;
    }

    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
    {
        return null;
    }

    public System.CodeDom.CodeTypeDeclaration ProcessImportedType(
        System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit)
    {
        return null;
    }
}