将事件标记为DataContractSerializer的NonSerializable

时间:2012-07-09 08:10:26

标签: c# events datacontractserializer

我在RelayCommand的实现中有以下事件:

public event EventHandler CanExecuteChanged
{
  add { CommandManager.RequerySuggested += value; }
  remove { CommandManager.RequerySuggested -= value; }
}

现在我正在使用DataContractSerializer。我知道在使用DataContractSerializer时,所有事件都必须标记为[field:NonSerialized]。但在这种情况下,这不起作用,因为我的CanExecuteChanged事件只是一个没有私有字段的属性。

如何将此属性标记为NonSerializable

修改

以下是整个RelayCommand类:

[DataContract]
public class RelayCommand : ICommand
{

  [field:NonSerialized]
  readonly Action<object> _execute;

  [field:NonSerialized]
  readonly Predicate<object> _canExecute;

  public RelayCommand(Action<object> execute)
    : this(execute, null)
  {
  }

  public RelayCommand(Action<object> execute, Predicate<object> canExecute)
  {
    if (execute == null)
      throw new ArgumentNullException("execute");

    _execute = execute;
    _canExecute = canExecute;
  }

  [DebuggerStepThrough]
  public bool CanExecute(object parameters)
  {
    return _canExecute == null ? true : _canExecute(parameters);
  }

  public event EventHandler CanExecuteChanged
  {
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
  }

  public void Execute(object parameters)
  {
    _execute(parameters);
  }
}

当我尝试执行DataContractSerializer时,我收到以下错误:

  

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

1 个答案:

答案 0 :(得分:1)

这就是我从link you gave me in the comment

更新样本的方法
[Serializable]
public abstract class BaseClass
{
    public string Name { get; set; }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
}

public class DerivedClass : BaseClass
{
    public int Age { get; set; }
}


class Program
{
    static void Main(string[] args)
    {
        var derivedClass = new DerivedClass { Name = "Test", Age = 10 };
        derivedClass.CanExecuteChanged += (sender, eventArgs) => Console.WriteLine("hello");

        var serializer = new DataContractSerializer(typeof(DerivedClass));
        using (var stream = new FileStream("d:\\test.txt", FileMode.Create, FileAccess.ReadWrite))
        {
            serializer.WriteObject(stream, derivedClass);
        }
    }
}

它没有任何例外。