【问题标题】:Conversion of the type of a Template class?Template类的类型转换?
【发布时间】:2010-11-07 21:17:26
【问题描述】:

我有一个名为“baseClass”的类。 从这个类我继承了一个类名“inheritedClass”(公共类inheritedClass:baseClass)

baseClass 包含一个返回HashSet<baseClass> 的公共函数。从inheritedClass调用时,返回类型显然还是HashSet<baseClass>,但我需要一个HashSet<inheritedClass>

转换 ala (HashSet<inheritedClass>)returnValue,其中 returnValue 的类型为 HashSet<baseClass> 不起作用。

有没有办法将HashSet-Type从baseClass转换为inheritedClass,而无需手动转换每个元素?

提前致谢, 弗兰克

【问题讨论】:

  • 什么? (15 个字符限制)
  • 你说你想从HashMap转换为HashMap,但那是同一个类。我在这里错过了什么吗?
  • 您缺少未引用的类型参数 :)
  • 你可以用一个通用的基类来做到这一点,看看我的答案..
  • 其次,如果可以使用泛型来完成,为什么还要增加转换开销。

标签: c# generics templates type-conversion


【解决方案1】:

解决办法

//**Your BaseClass**
public class BaseClass<T> where T : BaseClass<T>
{
    public HashSet<T> GetHashSet()
    {
        HashSet<T> _hSet = new HashSet<T>();
        //do some work              
        //create a HashSet<T> and return;              
        return _hSet;
    }
}
//**Your Inherited/Derived Class**
public class InheritedClass : BaseClass<InheritedClass>
{
    //you have the method inherited as you need.}
}

【讨论】:

  • 我建议在泛型类型中添加 where 子句: where T : BaseClass
  • @Oliver:谢谢 Oliver,我现在添加了一个适当的 where 子句。现在好像可以了?
【解决方案2】:

您真的是指标签中的 C# 吗? HashMap 是 Java 类型。而且它通常有两个类型参数而不是一个...

在 C# 中,泛型类始终是不变的。 一些接口在C# 4中变体,但很少(只有那些在输出位置使用类型参数的接口,例如@ 987654322@,或在输入位置使用类型参数,例如IComparable&lt;T&gt;)。

如果您可以提供有关您的情况的更准确信息,我们可能会帮助您想出一个简单的解决方案 - 特别是如果您可以使用带有 Cast&lt;T&gt;() 方法的 LINQ。

编辑:好的,HashSet&lt;T&gt;

HashSet<BaseType> baseSet = ...;
var derivedSet = new HashSet<DerivedType>(baseSet.Cast<DerivedType>());

请注意,即使使用 C# 4,这也是必要的,因为编译器不知道 baseSet 中的每个值都是 DerivedType 的实例 - 必须进行执行时检查。反过来(从HashSet&lt;DerivedType&gt; 创建HashSet&lt;BaseType&gt;在 C# 4 中工作。

进一步编辑:如果您只想使用UnionWith,则不需要HashSet&lt;DerivedType&gt; - 它需要IEnumerable&lt;DerivedType&gt;。我建议你这样做:

HashSet<BaseType> baseSet = ...;
HashSet<DerivedType> derivedSet = ...;

derivedSet.UnionWith(baseSet.Cast<DerivedType>());

【讨论】:

  • Arr ... 我提到 HashSet,而不是 HashMap。从我读到的您的回答中,无法转换 HashSet-Type 并且必须手动进行,对吗?问题背后是什么:我想使用HashSet的Union-method,所以我需要提供一个HashSet类型的参数,但是我的函数返回HashSet
  • UnionWith 方法,而不是 Union 方法
  • Cast() 是我想要的,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 2022-11-18
  • 2022-08-18
  • 2012-02-23
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多