开发者

ref argument in C#

开发者 https://www.devze.com 2023-03-05 19:29 出处:网络
First of all I am new to C# programming. I read the parameter of ImageObj.getBounds(ref GraphicsUnit unit);

First of all I am new to C# programming.

I read the parameter of

ImageObj.getBounds(ref GraphicsUnit unit);
开发者_高级运维

When I tried this,

ImageObj.getBounds(ref GraphicsUnit.Pixel);

I still got the error. But this seemed to work perfectly fine.

GraphicsUnit u = GraphicsUnit.Pixel;
ImageObj.getBounds(ref u);

What is the difference between the two and how is the first wrong? Thank You.


GraphicsUnit.Pixel is a property, you can not pass properties with ref/out parameters in C#. It's because ref/out is like pointer to pointer in other languages but property is not a variable - it's a 2 methods: getter and setter, so, you can't pass a pointer to pointer to value because you haven't value itself.

Added: Ok, GraphicsUnit.Pixel actually is an enum member - you also can't pass it with ref/out parameters because it's a constant.


GraphicsUnit.Pixel is a constant, as it's a member of an enumeration. As such, it can't be passed in to a function that expects a reference to a GraphicsUnit - getBounds may try to modify the value and this obvsiouly can't work.


The ref keyword must refer to a variable. A property isn't a variable. It's a special kind of member that wraps a backing field (which is a variable you can use with ref). Additionally, ref marks a variable to be modified by the method; that means if it's a reference to something, the reference is changed, not the object being referenced.

The second snippet works because you're assigning the contents of GraphicsUnit.Pixel to a local variable to be manipulated by the method.

0

精彩评论

暂无评论...
验证码 换一张
取 消