Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

properties - C# readonly vs Get

Are there any differences between the readonly modifier and get-only properties?

Example:

public class GetOnly
{
    public string MyProp { get; }
}

public class ReadOnly
{
    public readonly string MyProp;
}

Bonus: is there a way to make an interface that works with both? (to use with generics)

public interface ISomething
{
    public string MyProp { get; }
}

public class GetOnly : ISomething
{
    public string MyProp { get; }
}

public class ReadOnly : ISomething // Cannot implement
{
    public readonly string MyProp;
}

Many thanks in advance!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're fundamentally misunderstanding the meaning of both of those definitions. Only exposing the getter says nothing about whether or not a value is read-only.

While in this trivial example:

public class GetOnly
{
    public string MyProp { get; }
}

We can say that MyProp will never change its value, we cannot always say that a getter-only property will not have its value changed. An example of this is a situation where we cannot see the implementation of GetOnly, and only know about the public definition - For example, if you were working with a closed-source third party library.

A clearer example is this:

public interface ISomething
{
    string MyProp { get; }
}

This interface does not say that MyProp is read-only. It says that you cannot change the property. It says nothing about the behavior of the property. Even worse, it only says you cannot change the property when explicitly casting as ISomething.

It's entirely possible to implement the interface like so (even though the interface only exposes the getter):

public class GetOnly : ISomething
{
    public string MyProp { get; set; }
}

readonly is a modifier which explicitly enforces the fact that the value will not ever change, except in the declaration or constructor (barring workarounds like reflection).

However, readonly cannot work on properties, as properties are simply syntactic sugar for get/set methods. Further, interfaces only define methods, and as such you cannot define fields (and by extension, readonly fields).

So to answer your question: Yes, they are worlds apart, and are only similar on the surface.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...