这是处理泛型的唯一属性的好方法吗?

时间:2010-12-29 13:28:50

标签: c# generics

我有一个泛型类,它代表一个目前只有两种类型的文档。 Type1或Type2。大多数方法和属性都适用于两种类型,但标题不同。我想知道的是,是否有更好的方法来处理这个问题?谢谢!

[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和Type2是使用xsd.exe生成的,所以我可能会更改它们虽然可能会添加一个readonly xml ignored属性来获取Type1和Type2中的标题是否一致?

3 个答案:

答案 0 :(得分:3)

使用通用接口并在每个类中实现它。如果您不想更改原始类,可以尝试在实现此接口的每个类周围添加包装器。

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等。

答案 1 :(得分:1)

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;
    }

答案 2 :(得分:0)

XSD也可以处理继承。定义基本complexType(可能使用abstract =“true”),然后创建2个complexType,扩展基类。如果从中生成代码,它也会反映这种继承。

相关问题