在第一次尝试中,我试图通过向 int 或字符串注入 DialogBoxFactory 来保留变量的引用 IDialogFooterText ,并在我的工厂中调用'GetFooterDisplay()',然后返回一个字符串。我正在模拟对话框页面增量,并应该接收更新的页面索引。
这不能正常工作(然后我找到Eric Lippert的论坛答案,概述了我无法将ref参数存储在外部类'方法中并尝试其他路径的原因。
我的第二次尝试确实有效,但它似乎更脏,因为在 DialogFooterPagenum 我明确知道 DialogBoxFactory 的工厂类型。有什么其他方法可以获得页面索引而无需直接引用工厂实例化 IDIalogFooterText ?
public class DialogBoxFactory
{
public int _currentPageIndex = 0;
private string[] _dialogText = new string[10]; //filled with dialog content
//an example I've left to demonstrate the need for injecting different parameter types in their constructors
//private IDialogFooterText = new DialogFooterText( "ok" );
private IDialogFooterText _footerText = new DialogFooterPagenum( ref _currentPageIndex, dialogText.Length );
void Start(){
_currentPageIndex +=1;
Debug.Log( _footerText.GetFooterDisplay() );
//expecting the log to show "1/10"
}
}
public class DialogFooterPagenum : IDialogFooterText
{
private int _pageIndex;
private int _dialogLength;
public DialogFooterPagenum( ref int p_pageIndex, int p_dialogLength ){
_pageIndex = p_pageIndex;
_dialogLength = p_dialogLength;
}
public string GetFooterDisplay(){
return _pageIndex.ToString() + " / " + _dialogLength;
}
}
第二次尝试版本 - 自参考无法正常工作后重做
public class DialogBoxFactory
{
public int _currentPageIndex = 0;
private string[] _dialogText = new string[10]; //filled with dialog content
//an example I've left to demonstrate the need for injecting different parameter types in their constructors
//private IDialogFooterText = new DialogFooterText( "ok" );
private IDialogFooterText _footerText = new DialogFooterPagenum( this, dialogText.Length );
void Start(){
_currentPageIndex +=1;
Debug.Log( _footerText.GetFooterDisplay() );
//expecting the log to show "1/10"
}
}
public class DialogFooterPagenum : IDialogFooterText
{
private int _dialogLength;
private DialogBoxFactory _factory;
//this works now but is unacceptable since I wish this class to be unaware of the factory instantiating this class.
public DialogFooterPagenum( DialogBoxFactory p_factory , int p_dialogLength ){
_factory = p_factory;
_dialogLength = p_dialogLength;
}
public string GetFooterDisplay(){
return _factory._currentPageIndex.ToString() + " / " + _dialogLength;
}
}
答案 0 :(得分:1)
我看不出有任何理由不在IDialogFooterText
实施中存储当前页面索引:
interface IDialogFooterText
{
string GetFooterDisplay();
int CurrentPageIndex { get; set; }
}
public class DialogBoxFactory
{
IDialogFooterText _footerText = // ...
void Start()
{
_footerText.CurrentPageIndex += 1;
Debug.Log( _footerText.GetFooterDisplay() );
}
}
答案 1 :(得分:0)
我还没有深入阅读你的问题。我只能看到您需要引用可变page index
到DialogFooterPagenum
。 PageIndex
班可以解决问题吗?
class PageIndex{
private int index;
public int Index{get{return index;}
set{
index = value;
OnPageIndexChange();
}
}
public Action OnPageIndexChange{get;set;} // change this to event-based
}
这样您就可以保留对页面索引的引用。