简体   繁体   中英

What happens when you try to set value to a read-only property?

Recently I have been working with C# and I ran into this curious problem. I tried to set a value to the read-only property of the excel chart class, before I read the documentation and discovered that the property is read-only.

var charts= worksheet.ChartObjects() as xcel.ChartObjects;
var chartObj = charts.Add(60,10,200,400) as xcel.ChartObject;
var chart = chartObj.Chart;
chart.Name = "GicsSectorIndustry";   <--

I get this error:

Insufficient memory to continue the execution of the program

When I remove that line, the code works perfectly, so it led me to wonder what happens behind the scenes when I try to set a value for the read-only property that causes it to "run out of memory".

If it was read-only, you could not compile that code. This means it's not read-only but the documentation says to treat it as read-only.


Rephrased question: What happens when you try to assign to an assignable property that the documentation says to treat as read-only?

Short answer: Does it matter?

Long answer: Without the source, it's very hard to tell. You could use ILSpy to debug it but the short answer still applies.

It seems you are reading the wrong documentation.

I had inquired as to what namespace the class you were using came from. According to the documentation for the Interop assembly, the signature is:

public:
property System::String ^ Name { System::String ^ get(); void set(System::String ^ value); };

As you can see, there is a setter.

You can read more about it here .

There exists another version (a wrapper, I imagine) from Tools for Office. The signature for that one does not provide a setter:

public string Name { get; }

More information on that one can be found here .

Interop assemblies bridge between managed and unmanaged code so my educated guess is that the second version (wrapper) probably exists to manage issues like the one you are experiencing, or it could be another Interop implementation all together.

As others have stated, if no setter was provided, your code just wouldn't compile but in this case it does. It's just something goes wrong under the covers.

UPDATE:

I found the following concerning the difference between the two implementations:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/86a62151-fbf0-4584-a68c-83060fb95c3d/officeinteropexcel?forum=vsto

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM