我如何要求参数数组中的所有对象都作为 out 传递?在我的以下代码中,我知道它失败了,因为我的原始参数从未被分配,因此为空。即使我认为它们会作为参考传递而无需明确说明,但它们似乎并非如此。结果,我不得不尝试将所有这些作为输出参数传递。
这是我认为重要的代码部分。
ChatController(删除了一些元素)
class ChatController : ControllerBase
{
#region Views
ChatAreaView viewChatArea;
UserListView viewUserArea;
MessageView viewMessageArea;
LoginPromptView viewLoginPrompt;
#endregion
#region ViewModels
ChatAreaViewModel viewModelChatArea;
UserAreaViewModel viewModelUserArea;
MessageAreaViewModel viewModelMessageArea;
LoginPromptViewModel viewModelLoginPrompt;
#endregion
public override void CreateViewsAndViewModels()
{
//InitializeViewAndViewModel(out viewChatArea, out viewModelChatArea);
//InitializeViewAndViewModel(out viewMessageArea, out viewModelMessageArea);
//InitializeViewAndViewModel(out viewUserArea, out viewModelUserArea);
//InitializeViewAndViewModel(out viewLoginPrompt, out viewModelLoginPrompt);
InitializeViewsAndViewModels(new FrameworkElement[] { viewChatArea, viewUserArea, viewMessageArea, viewLoginPrompt },
new object[] { viewModelChatArea, viewModelUserArea, viewModelMessageArea, viewModelLoginPrompt });
}
}
ControllerBase(删除了一些元素)
public abstract class ControllerBase : PrismBase
{
public void InitializeViewAndViewModel<TView, TViewModel>(out TView view, out TViewModel viewModel)
where TView : FrameworkElement, new()
where TViewModel : new()
{
view = new TView();
viewModel = new TViewModel();
view.DataContext = viewModel;
}
public void InitializeViewsAndViewModels(FrameworkElement[] views, object[] viewModels)
{
if (views.Length != viewModels.Length)
throw new ArgumentOutOfRangeException("views and viewModels must have the same number of elements.");
for (int i = 0; i < views.Length -1 ; i++)
InitializeViewAndViewModel(out views[i], out viewModels[i]);
}
}
问题区域在这里
public void InitializeViewsAndViewModels(FrameworkElement[] views, object[] viewModels)
{
}
当方法返回时,我传递给方法的所有这些对象都保持为空。
InitializeViewsAndViewModels(new FrameworkElement[] { viewChatArea, viewUserArea, viewMessageArea, viewLoginPrompt },
new object[] { viewModelChatArea, viewModelUserArea, viewModelMessageArea, viewModelLoginPrompt });
我想要求将所有视图和viewModels数组对象作为 out 传递,但我似乎只能要求将整个数组本身作为 out 传递。
我可以在这里做什么?
编辑:整个问题似乎源于该方法的复数形式,如上所述。如果我摆脱了它,我只是这样做了......
public override void CreateViewsAndViewModels()
{
InitializeViewAndViewModel(out viewChatArea, out viewModelChatArea);
InitializeViewAndViewModel(out viewMessageArea, out viewModelMessageArea);
InitializeViewAndViewModel(out viewUserArea, out viewModelUserArea);
InitializeViewAndViewModel(out viewLoginPrompt, out viewModelLoginPrompt);
//InitializeViewsAndViewModels(new FrameworkElement[] { viewChatArea, viewUserArea, viewMessageArea, viewLoginPrompt },
// new object[] { viewModelChatArea, viewModelUserArea, viewModelMessageArea, viewModelLoginPrompt });
}
一切都很顺利。