【问题标题】:Is this a good way to handle unique properties for a generic?这是处理泛型独特属性的好方法吗?
【发布时间】:2010-12-29 22:07:44
【问题描述】:

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

[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 生成的,因此我犹豫是否要更改它们,尽管可能会添加一个只读的 xml 忽略属性以使 Type1 和 Type2 中的标题保持一致?

【问题讨论】:

    标签: c# generics


    【解决方案1】:

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

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

    【讨论】:

    • 如果您这样做,并且我认为您应该这样做,请确保在泛型类的 T 上放置一个限制器,这样您就不必检查 Document 实际上是一个 IHasTitle。跨度>
    • 如果生成的代码支持它,我会使用部分类。修改生成的代码文件通常是坏事。
    【解决方案2】:

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

    【讨论】:

    • 它确实会生成部分类,我会这样做,但生成的类名并不是那么直观,而不是更改生成的类名我将使用包装器的想法。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2019-04-28
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多