Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

c# - 'ref'和'out'关键字有什么区别?(What's the difference between the 'ref' and 'out' keywords?)

I'm creating a function where I need to pass an object so that it can be modified by the function.

(我正在创建一个需要传递对象的函数,以便可以通过该函数对其进行修改。)

What is the difference between:

(之间有什么区别?)

public void myFunction(ref MyClass someClass)

and

(和)

public void myFunction(out MyClass someClass)

Which should I use and why?

(我应该使用哪个?为什么?)

  ask by TK. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

ref tells the compiler that the object is initialized before entering the function, while out tells the compiler that the object will be initialized inside the function.

(ref告诉编译器在进入函数之前该对象已初始化,而out告诉编译器该对象将在函数内进行初始化。)

So while ref is two-ways, out is out-only.

(因此,当ref是双向的时, out是仅输出的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...