c#XmlC类提供特定值

c#XmlC类提供特定值,c#,xml,serialization,C#,Xml,Serialization,我在上一些c#的课。它们需要序列化为XML以匹配现有模式,但我希望在代码中构建验证。e、 g.类似下面的内容 public class Address { public AddressLineType AddressLine1 {get;set;} public AddressLineType AddressLine2 {get;set;} public ShortAddressLineType AddressTown {get;set;}

我在上一些c#的课。它们需要序列化为XML以匹配现有模式,但我希望在代码中构建验证。e、 g.类似下面的内容

public class Address {
        public AddressLineType AddressLine1 {get;set;}
        public AddressLineType AddressLine2 {get;set;}
        public ShortAddressLineType AddressTown {get;set;}
        public ShortAddressLineType AddressCounty {get;set;}
        public PostCodeType PostCode {get;set;}
    }

    public class SimpleString {
        public string Value {get;set;}
        public override string ToString() {
            return Value;
        }
    }

    public class AddressLineType : SimpleString {
        static readonly int maxLength = 60;
        public static explicit operator AddressLineType(string v) {
            if(!(v.Length < maxLength)) throw new Exception("String is to long!");
            AddressLineType s = new AddressLineType();
            s.Value = v;
            return s;
        }
    }

    public class ShortAddressLineType : SimpleString {
        static readonly int maxLength = 30;
        public static explicit operator ShortAddressLineType(string v) {
            if(!(v.Length < maxLength)) throw new Exception("String is to long!");
            ShortAddressLineType s = new ShortAddressLineType();
            s.Value = v;
            return s;
        }
    }

    public class PostCodeType : SimpleString {
        public static explicit operator PostCodeType(string v) {
        Regex regex = new Regex(""); //PostCode pattern..
            if(!(regex.IsMatch(v))) throw new Exception("Regex Validation Failed.");
            PostCodeType s = new PostCodeType();
            s.Value = v;
            return s;
        }
    }

[XmlText]
添加到
,使
虚拟(或具有一些通知事件),并在setter中执行验证。请参阅:。这是否回答了您的问题,还是您需要更具体的答案?在显式操作符中抛出异常是否重要?这比我想象的要简单,并且确实回答了这个问题。但是,如何改进字符串验证?我不确定是否理解您的后续问题。您不能添加一个
受保护的虚拟void OnValueChanged()
方法,并在
SimpleString
的各个子类中重写它吗?
Address address = new Address();
address.AddressLine1 = (AddressLineType) "3 The Street";
address.AddressLine2 = (AddressLineType) "Foo Town";

XmlSerializer serializer = new XmlSerializer(typeof(Address));
serializer.Serialize(Console.Out, address);