C#:如何在函数参数中传递对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/276253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: How do you pass an object in a function parameter?
提问by
C#: How do you pass an object in a function parameter?
C#:如何在函数参数中传递对象?
public void MyFunction(TextBox txtField)
{
txtField.Text = "Hi.";
}
Would the above be valid? Or?
以上是否有效?或者?
采纳答案by Timothy Carter
So long as you're not in a different thread, yes the code sample is valid. A textbox (or other windows forms items) are still objects that can be passed to and manipulated by methods.
只要您不在不同的线程中,代码示例就是有效的。文本框(或其他窗体项)仍然是可以传递给方法并由方法操作的对象。
回答by Jon Skeet
Yup, that will work. You're not actually passing an object - you're passing in a referenceto the object.
是的,这会奏效。您实际上并没有传递对象 - 您正在传递对该对象的引用。
See "Parameter passing in C#"for details when it comes to pass-by-ref vs pass-by-value.
有关传递引用与传递值的详细信息,请参阅“C# 中的参数传递”。
回答by Marc Gravell
For any reference-type, that is fine - you have passed the referenceto the object, but there is only one object, so changes are visible to the caller.
对于任何引用类型,这都很好 - 您已将引用传递给对象,但只有一个对象,因此调用方可以看到更改。
The main time that won'twork is for "structs" (value-types) - but they really shouldn't be mutable anyway (i.e. they shouldn't really have editable properties).
主时间不会工作,是“结构”(值类型) -但他们真的不应该是可变的,反正(即它们不应该真的有可编辑的属性)。
If you neededto do this with a struct, you could add "ref" - i.e.
如果您需要使用结构来执行此操作,则可以添加“ref”-即
public void MyFunction(ref MyMutableStruct whatever)
{
whatever.Value = "Hi."; // but avoid mutable structs in the first place!
}