C# 是否可以使HashSet子类成为字典的子类?

C# 是否可以使HashSet子类成为字典的子类?,c#,generics,inheritance,C#,Generics,Inheritance,我试图创建一个泛型类型来处理C#实体之间的所有引用 在一种情况下,reference只是一个intID,因此要记住它在何处被使用,正确的数据结构应该是HashSet 在另一个场景中,可以在树结构中使用实体,因此我需要记住intId和作为对象集合的路径。正确的数据结构应该是字典 以下是我到目前为止的情况: public class References<TValue> : Dictionary<int, TValue> { } public class Referen

我试图创建一个泛型类型来处理C#实体之间的所有引用

  • 在一种情况下,
    reference
    只是一个
    int
    ID,因此要记住它在何处被使用,正确的数据结构应该是
    HashSet
  • 在另一个场景中,可以在树结构中使用实体,因此我需要记住
    int
    Id和作为对象集合的路径。正确的数据结构应该是
    字典
以下是我到目前为止的情况:

public class References<TValue> : Dictionary<int, TValue>
{
}

public class References : HashSet<int>
{
}

public class MyEntityWithDefaultReferences
{
    public References References;
}

public class MyEntityWithPathReferences<PathType>
{
     public References<PathType> References;
}
公共类引用:字典
{
}
公共类引用:HashSet
{
}
公共类MyEntityWithDefaultReferences
{
公众参考资料;
}
公共类MyEntityWithPathReferences
{
公众参考资料;
}

有没有办法让第二个
引用继承第一个类?所以我可以在任何地方使用父类。

好吧,这样怎么样

public interface MyReference{
    int Id{get;set;}
}

public class SimpleReference : MyReference
{
    public int Id{get;set;}
}
public class CompoundReference<T> : MyReference
{
    public int Id{get;set;}
    public T TValue{get;set;}
}

public class ReferenceCollection : KeyedCollection<int, MyReference>
{
    protected override int GetKeyForItem(MyReference item)
    {
        return item.Id;
    }
}
公共接口MyReference{
int Id{get;set;}
}
公共类SimpleReference:MyReference
{
公共int Id{get;set;}
}
公共类CompoundReference:MyReference
{
公共int Id{get;set;}
公共T值{get;set;}
}
公共类引用集合:KeyedCollection
{
受保护的覆盖int GetKeyForItem(MyReference项)
{
返回项目.Id;
}
}
你可以用like

SimpleReference sr = new SimpleReference(){Id=1};
CompoundReference<string> cr = new CompoundReference<string>(){Id=2,TValue="Test"};

ReferenceCollection col = new ReferenceCollection();
col.Add(sr);
col.Add(cr);
Console.WriteLine(col.Contains(1)); //true
Console.WriteLine(col.Contains(2)); //true
Console.WriteLine(col.Contains(3)); //false
var i1 = col[1]; //returns sr
var i2 = col[2]; //return cr
SimpleReference sr=newsimplereference(){Id=1};
CompoundReference cr=new CompoundReference(){Id=2,TValue=“Test”};
ReferenceCollection col=新的ReferenceCollection();
加上校(sr);
col.Add(cr);
控制台写入线(列包含(1))//符合事实的
控制台写入线(列包含(2))//符合事实的
控制台写入线(列包含(3))//错误的
var i1=列[1]//返回sr
var i2=col[2]//返回cr

c#没有多重继承。您可以使用多个接口。这也适用于
HashSet
Dictionary
。也许你可以使用?@磁控管如果我只需要key@Mhd让我看看我是否理解正确,您有两个类,一个是id,另一个是id+a值,您想将它们都存储在同一个集合中吗?