Warm tip: This article is reproduced from serverfault.com, please click

How to hide set method of an implemented property from an interface in C#?

发布于 2011-04-30 20:15:01

Greetings everyone...

If I have the following interface:

interface IMyInterface
{
    int property { get; set; }
}

And the following implementation:

class MyClass : IMyInterface
{
// anything
}

How can I hide the set method of property from the instances of MyClass... In other words, I don't want the set method of property to be public, is that possible?

It would be easy to do with abstract class:

abstract class IMyInterface
{
    int property { get; protected set; }
}

Then I could only set the property within the class that implements the abstract class above...

Questioner
Girardi
Viewed
0
Roja Buck 2011-05-01 04:30:44

If you use the following interface the set method will be unavailable when classes are manipulated via the interface:

interface IMyInterface
{ 
   int property { get; }
}

You could then implement the class like this:

class MyClass : IMyInterface
{
  int property { get; protected set; }
}