Inheritance right

I have a class:

internal class Stage { public long StageId { get; set; } public string StageName { get; set; } public int? Order { get; set; } public Stage() { Order = 0; } } 

I also have:

 public class GroupStage : Stage { private override long StageId { set { StageId = value; } } public GroupStage() : base() { } public void InsertStage(long groupId) { } public static void SetStageOrder(long stageId, int order) { .... } public static void DeleteStage(long stageId) { .... } public static GroupStage[] GetStages(long groupId) { .... } } 

and

 public class TaskStage : Stage { public DateTime? Time { get; set; } public TaskStage() : base() { .... } public static Stage GetNextTaskStage(Guid companyId, long taskId) { .... } public static Stage[] GetTaskStages(Guid companyId, long taskId) { .... } } 

This does not work, and I get an exception: Inconsistent availability: Stage base class is less accessible than GroupStage class

I want the Stage class to be private and without access except GroupStage and TaskStage . I also want to make StageId private in GroupStage and TaskStage . How can I do this without duplicating Stage members in GroupStage and TaskStage ?

+4
source share
4 answers

You cannot make a derived class more accessible than a base class. You can also make TaskStage and GroupStage internal, and then inherit and publish public interfaces so that only the interface is visible outside of your assembly.

 public interface IGroupStage { public string StageName{ get; set; } ... } interal class GroupStage : IGroupStage { ... } 
+4
source

You must make you class Stage public or protected. if you make it abstract, it cannot be created at this level, so if you publish it you need not worry about it being created as a base class

+1
source

Make it protected instead of private. If you make it protected, you give classes that inherit from it methods of calling in the base class and inherit members of the base class.

+1
source

What you probably really want is a stage, which is an abstract base class that, therefore, cannot be directly created, regardless of its accessibility modifier. Change the stage definition:

 public abstract class Stage { protected long StageId { get; set; } public string StageName { get; set; } public int? Order { get; set; } protected Stage() { Order = 0; } } 

A protected modifier means that your derived classes will be able to access this member, but it will not be available outside these classes.

+1
source

Source: https://habr.com/ru/post/1343350/


All Articles