我不是在讨论指向const值的指针,而是指向const指针本身.
我正在学习C和C++,超越了基本的东西,直到今天我才意识到指针是通过值传递给函数的,这是有道理的.这意味着在函数内部,我可以使复制的指针指向其他值,而不会影响来自调用者的原始指针.
那么有一个函数头是什么意思:
void foo(int* const ptr);
Run Code Online (Sandbox Code Playgroud)
在这样的函数里面你不能让ptr指向别的东西因为它是const并且你不希望它被修改,但是这样的函数:
void foo(int* ptr);
Run Code Online (Sandbox Code Playgroud)
工作也一样好!因为无论如何都会复制指针,即使您修改了副本,调用者中的指针也不会受到影响.那么const的优势是什么?
我有这个方法及其委托,用于从我的WinForms应用程序中的任何线程将文本附加到GUI中的多行TextBox:
private delegate void TextAppendDelegate(TextBox txt, string text);
public void TextAppend(TextBox txt, string text)
{
if(txt.InvokeRequired)
txt.Invoke(new TextAppendDelegate(TextAppend), new object[] {txt, text });
else
{
if(txt.Lines.Length == 1000)
{
txt.SelectionStart = 0;
txt.SelectionLength = txt.Text.IndexOf("\n", 0) + 1;
txt.SelectedText = "";
}
txt.AppendText(text + "\n");
txt.ScrollToCaret();
}
}
Run Code Online (Sandbox Code Playgroud)
它工作得很好,我只是从任何线程调用TextAppend(myTextBox1,"Hi Worldo!")并更新GUI.现在,有没有办法将调用TextAppend的委托传递给另一个项目中的一个实用程序方法,而不发送对实际TextBox的任何引用,这可能是调用者看起来像这样:
Utilities.myUtilityMethod(
new delegate(string str){ TextAppend(myTextBox1, str) });
Run Code Online (Sandbox Code Playgroud)
在被调用者中,定义类似于:
public static void myUtilityMethod(delegate del)
{
if(del != null) { del("Hi Worldo!"); }
}
Run Code Online (Sandbox Code Playgroud)
因此,当调用此函数时,它会调用带有该字符串的TextAppend方法以及调用者想要使用的预定义TextBox.这可能还是我疯了?我知道有更简单的选项,如使用接口或传递TextBox和委托,但我想探索这个解决方案,因为它似乎更优雅,并隐藏来自被调用者的东西.问题是我在C#中仍然是新手并且几乎不了解代理,所以请帮助我使用实际的语法.
提前致谢!