我有一个Dictionary以枚举值作为键并返回一个对象作为值.对象构造函数涉及调用一个可能需要很长时间并占用大量内存的方法.现在,即使只需要一个对象,也会创建字典中的每个可能对象.有没有办法只创建键指定的对象?
private DataPreparer SetUpOuDataPreparer()
{
Scope = _activeDirectoryScope.Context;
var activeDirectorySearcher = new ActiveDirectorySearcher(
_activeDirectoryScope);
var ouDataPreparers = new Dictionary<QueryType, DataPreparer>
{
[OuComputers] = new DataPreparer
{
Data = activeDirectorySearcher.GetOuComputerPrincipals(),
Attributes = DefaultComputerAttributes
},
[OuGroups] = new DataPreparer
{
Data = activeDirectorySearcher.GetOuGroupPrincipals(
CancellationToken),
Attributes = DefaultGroupAttributes
},
[OuUsers] = new DataPreparer
{
Data = activeDirectorySearcher.GetOuUserPrincipals(),
Attributes = DefaultUserAttributes
},
[OuUsersDirectReports] = new DataPreparer
{
Data = activeDirectorySearcher.GetOuUsersDirectReports(
CancellationToken),
Attributes = DefaultUserDirectReportsAttributes
},
[OuUsersGroups] = new DataPreparer
{
Data = activeDirectorySearcher.GetOuUsersGroups(
CancellationToken),
Attributes = DefaultUserGroupsAttributes
}
};
return ouDataPreparers[QueryType];
}
Run Code Online (Sandbox Code Playgroud)
该方法创建了所有五个DataPreparers,每个都有一个昂贵的方法调用ActiveDirectorySearcher.我想以某种方式只创建DataPreparer由QueryType键指定,最好不使用switch或if/else.我从那些改为Dictionary更好的格式/风格.
我会考虑在你的课堂上使用a Lazy<T>作为你的Data财产DataPreparer.这样,它只会activeDirectorySearcher.GetOuGroupPrincipals在实际需要的时候调用,而不是在创建时立即调用.