[英]Return HashSet<T> from HashSet of generic type in generic function
我有一個Dictionary<Type, HashSet<GenericType>>
,可用於保存數據,並且我試圖制作一個返回給定泛型T : GenericType
HashSet之一的函數。
基本上
Dictionary<Type, HashSet<GenericType>> data;
public HashSet<T> Get<T>() where T : GenericType
{
var tp = typeof(T);
//....check if its in the dictionary, fill if not....
return data[tp];
}
當然這是無效的。 但是我很難弄清楚應該怎么做。 我覺得返回T
是最佳選擇,因為您可以執行以下操作:
Get<Derived>().Where(x => x.DerivedProperty == someValue)
但是我唯一想到的是每次調用Get
都創建一個新的HashSet<T>
,然后使用foreach循環強制轉換並從Dictionary中已經存在的HashSet中添加所有項,但這感覺像是浪費?
另一個想法是跳過HashSet並使用另一個(協變量?)集合。 但是,由於這些集合將保存大量數據,因此也不是最好的主意。
簡而言之,我想知道解決此問題的最佳方法是什么。
這就是我得到的結構。 在我的代碼結構中,包含data
的類型是一種服務類型。 它會通過反射在運行時加載和初始化。 之后,我從那里使用各種ServiceFactory來獲取該服務。
public class foo : Service
{
public Dictionary<Type, HashSet<BaseClass>> data = new Dictionary<Type, HashSet<BaseClass>>();
public T Get<T>() where T : BaseClass
{
var tp = typeof(T);
if (!data.ContainsKey(tp))
{
data.Add(typeof(Derived), new HashSet<BaseClass>() { new Derived(), new Derived(), new Derived() });
}
return data[tp];//this wont compile.
}
}
public class Derived : BaseClass
{
public int ExampleVariable {get;set;}
}
public abstract class BaseClass
{
// some things in here.
public void DoCommonStuff()
{
}
}
class program
{
static void Main(string[] args)
{
var service = ServiceFactory.GetService<foo>();
var collection = service.Get<Derived>();
}
}
我只需要更改字典的類型,然后將其強制轉換為Get
方法即可。 當然,絕對將您的詞典設為私有-然后,您可以確保只有您的代碼 (最好是只有Get
方法)才能訪問它:
// Any data[typeof(Foo)] value will be a HashSet<Foo>. Only
// the Get method should access this dictionary.
private readonly Dictionary<Type, object> data = new Dictionary<Type, object>();
public HashSet<T> Get<T>() where T : GenericType
{
var tp = typeof(T);
object value;
if (data.TryGetValue(tp, out value))
{
return (HashSet<T>) value;
}
var newSet = new HashSet<T>()
// Populate newSet here
data[tp] = newSet;
return newSet;
}
我在博客文章中對一個密切相關的問題進行了更多討論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.