내가있어 Dictionary<Type, HashSet<GenericType>>
내가 내 데이터를 저장하기 위해 사용하는, 그리고 나는 함수를 만들려고 노력하고 그 반환 제네릭 형식을 부여하는 HashSets 중 하나 T : GenericType
.
원래
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)
하지만 내가 생각한 유일한 것은 호출 HashSet<T>
될 때마다 새 Get
항목을 만든 다음 foreach-loop 캐스트를 사용하고 사전에 이미 존재하는 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;
}
블로그 게시물 에서 밀접하게 관련된 문제에 대해 좀 더 논의하고 있습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다