C#'s readonly vs C++'s const
This is mostly an understanding check, as I couldn't find a complete reference on this topic.
In C#, when I write readonly Foo myFoo
, I'm essentially saying myFoo
is a pointer to Foo
, and the pointer cannot be reassigned. To guarantee that the underlying Foo
can't be reassigned, I need a whole other class or interface ImmutableFoo
.
Now consider the construct List<Foo>
. It's basically a pointer to a list of pointers to Foo
, ie similar to vector<Foo *> *
in C++. There are three places where you could put const
in C++.
const vector<const Foo *> * const
So I think the equivalent of each of these is,
List<Foo> = vector<Foo *> * // No consts
ReadOnlyCollection<Foo> = const vector<Foo *> * // First const toggled
List<ImmutableFoo> = vector<const Foo *> * // Second const toggled
readonly List<Foo> = vector<Foo *> * const // Third const toggled
readonly ReadOnlyCollection<ImmutableFoo>
= const vector<const Foo *> * const // All consts toggled
Is this table of equivalencies correct?
Yes, I think you got it. I think this const to readonly translation is correct, even if you should not compare those two keywords . I think there are many other subtly and differently behaves between the C++ const and C# readonly keyword. Some of them are:
tbc...
链接地址: http://www.djcxy.com/p/87334.html