Is this a good way to handle unique properties for the general?

I have a general class, which is a document that can currently be of only two types. Type1 or Type2. Most methods and properties work fine for both types, but the name is different. What am I wondering if there is a better way to handle this? Thank!!

[XmlIgnore]
public string DocumentType
{
  get
  {
    return typeof(T).Name;
  }
}

[XmlIgnore]
public string DocumentTitle
{
  get
  {
    string retval = string.Empty;
    Object obj = Document;

    switch (DocumentType)
    {
      case "Type1":
        retval = ((Type1)obj).title.Text;
        break;
      case "Type2":
        retval = ((Type2)obj).Title;
        break;
    }
    return retval;
  }
}

Type1 and Type2 were generated using xsd.exe, so I'm embarrassed to change them, although perhaps adding the readonly xml ignored property to get the header in both Type1 and Type2, which is consistent?

+3
source share
3 answers

. , , .

interface IHasTitle
{
    string Title { get; }
}

class MyType1 : Type1, IHasTitle
{
    // Add constructors here.

    public string Title { get { return this.title.Text; } }
}

class MyType2 : Type2, IHasTitle
{
    // Add constructors here.
}

:

[XmlIgnore]
public string DocumentTitle
{
    get
    {
        IHasTitle hasTitle = Document;
        return hasTitle.Title;
    }
}

, IDocument , Name ..

+3

xsd.exe ? , , . ( .)

, , :

    public string ExtractDocumentTitle()
    {
        Type1 t1 = Document as Type1;
        if (t1 != null)
            return t1.title.Text;

        Type2 t2 = Document as Type2;
        if (t2 != null)
            return t2.Title;


        // fall-through & catch-all
        return String.Empty;
    }
+1

XSD . complexType (, abstract = "true" ), 2 complexType, . , .

0

Source: https://habr.com/ru/post/1782595/


All Articles