英文:
How to create Data structure like HashSet?
问题
创建一个类似于HashSet但存储不同类型而不是值的数据结构的最佳方法是什么?
如何简化这段代码,我觉得我做错了什么,遍历整个列表似乎是不必要的。
我拥有的示例代码如下:
public abstract class Foo {}
public class FooA : Foo {}
public class FooB : Foo {}
public class FooList : List<Foo>
{
public new void Add(Foo fooItem)
{
// 在不遍历的情况下进行处理
foreach (var item in this)
{
if (item.GetType() == fooItem.GetType())
return;
}
base.Add(fooItem);
}
}
这是它的用法:
FooA fooA = new FooA();
FooB fooB = new FooB();
FooB anotherFooB = new FooB();
FooList list = new FooList();
list.Add(fooA);
list.Add(fooB);
list.Add(anotherFooB);
foreach(var item in list)
{
Console.WriteLine(item);
}
/* 输出:
FooA
FooB
*/
英文:
What is the best way to make a data structure similar to HashSet but unique types instead of values.
How can I simplify this code, it seems to me that I'm doing something wrong and going through the whole list is unnecessary.
An example of what I have:
public abstract class Foo {}
public class FooA : Foo {}
public class FooB : Foo {}
public class FooList : List<Foo>
{
public new void Add(Foo fooItem)
{
// как то без перебора
foreach (var item in this)
{
if (item.GetType() == fooItem.GetType())
return;
}
base.Add(fooItem);
}
}
This is how it is used:
FooA fooA = new FooA();
FooB fooB = new FooB();
FooB anotherFooB = new FooB();
FooList list = new FooList();
list.Add(fooA);
list.Add(fooB);
list.Add(anotherFooB);
foreach(var item in list)
{
Console.WriteLine(item);
}
/* Output:
FooA
FooB
*/
答案1
得分: 1
你可以使用 HashSet<Type>
,例如。
using System;
using System.Collections;
using System.Collections.Generic;
...
public class FooList : IEnumerable<Type> {
private HashSet<Type> m_Types = new HashSet<Type>();
public bool Add(object value) => value is null
? false
: m_Types.Add(value.GetType());
public IEnumerator<Type> GetEnumerator() => m_Types.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => m_Types.GetEnumerator();
}
然后你可以使用你的代码:
FooA fooA = new FooA();
FooB fooB = new FooB();
FooB anotherFooB = new FooB();
FooList list = new FooList();
list.Add(fooA);
list.Add(fooB);
list.Add(anotherFooB);
foreach(var item in list)
{
Console.WriteLine(item);
}
并得到预期输出:
FooA
FooB
英文:
You can use HashSet<Type>
, e.g.
using System;
using System.Collections;
using System.Collections.Generic;
...
public class FooList : IEnumerable<Type> {
private HashSet<Type> m_Types = new HashSet<Type>();
public bool Add(object value) => value is null
? false
: m_Types.Add(value.GetType());
public IEnumerator<Type> GetEnumerator() => m_Types.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => m_Types.GetEnumerator();
}
Then you can use your code:
FooA fooA = new FooA();
FooB fooB = new FooB();
FooB anotherFooB = new FooB();
FooList list = new FooList();
list.Add(fooA);
list.Add(fooB);
list.Add(anotherFooB);
foreach(var item in list)
{
Console.WriteLine(item);
}
And get expected output:
FooA
FooB
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论