简体   繁体   中英

In c# how to prevent a class from being modified

Let's say I have an interface:

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
   bool Alive { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
}

That would not compile since Person does not implement the Alive Property.

What I would like to know is if there is a way to have the same behaviour, if Person adds an extra property that is not found in its interface.

interface IPerson
{
   int Age { get; set; }
   string Name { get; set; }
}

and a Class:

public class Person : IPerson
{
   public int Age { get; set; }
   public string Name { get; set; }
   public bool Alive { get; set; }  <---- This should prevent it from compiling as well.
}

I would want it to not compile as well, or at the very least give me a compile warning.

No. Interfaces define what members an object must implement. They cannot define members that an object can't implement. You could potentially use your own custom, or third party code analysis tools, to identify cases like this, but there is nothing in the language itself that would support it.

No it is not possible. Are you not trying to define a class itself here? Why do you really need an interface?

However, what you can achieve is make calls to your interface and not your class by doing

 IPerson person = new Person();

this way you limit the person object to access only the methods defined in your interface.

There is a way to do this, but not within the object and its a bit silly to use in construction of the object. Using Reflection , you can check the type of an instance of your object and iterate through its properties, throwing an exception if the count or names of properties do not match your desired instance. Please note that if you just check against the interface, implementing objects will pass, so you would check against the desired concrete type. I am on my phone or I'd add some sample code, will try to return to this later.

There is a way to do this, but not within the object and its a bit silly to use in construction of the object. Using Reflection , you can check the type of an instance of your object and iterate through its properties, throwing an exception if the count or names of properties do not match your desired instance. Please note that if you just check against the interface, implementing objects will pass, so you would check against the desired concrete type. I'm on my phone so no sample code. Will try to return to this later.

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