Home > Software design >  Derived class and Derived field. Change a few or all properties values
Derived class and Derived field. Change a few or all properties values

Time:03-31

Using C# 10 and Net 6 I have (simplified code):

public class DefaultsBase {
  public Int32 Repeats { get; set; } = 10;
}

public abstract class StrategyBase {

  public abstract String Name { get; }
  public abstract DefaultsBase Defaults { get; }

}

public class MonthlyStrategy : StrategyBase {

  public override String Name => "Monthly Strategy";
  public override MonthlyStrategyDefaults Defaults = new MonthlyStrategyDefaults();

  public String Street { get; }

  private class MonthlyStrategyDefaults : DefaultsBase {
    public Int32 Window { get; } = 20;
  };

  public MonthlyStrategy(String street, Action<MonthlyStrategyDefaults> defaultsConfiguration)  {

    defaultsConfiguration(Defaults);
    Street = street;

  }

}

What I am trying to accomplish is:

1 - Create Strategy classes that derive from StrategyBase;

2 - In each Strategy being able to create a StrategyDefaults derived from DefaulstBase.

3 - Use an Action in constructor to change a few or all Strategy's Defaults including the ones on DefaultsBase.

I am not sure if my implementation makes sense and I am also getting the errors:

public override MonthlyStrategyDefaults Defaults 
> The modifier 'override' is not valid for this item 

public MonthlyStrategy(String street, Action<MonthlyStrategyDefaults> defaultsConfiguration)
> Inconsistent accessibility: 
  parameter type 'Action<MonthlyStrategy.MonthlyStrategyDefaults>' is 
  less accessible than method 'MonthlyStrategy.MonthlyStrategy(string, Action<MonthlyStrategy.MonthlyStrategyDefaults>)

How to do this?

CodePudding user response:

first error

to override a property in the base class, it should has the same type and name

public override MonthlyStrategyDefaults Defaults = new MonthlyStrategyDefaults();

change it to

public override DefaultsBase Defaults = new MonthlyStrategyDefaults();

second error

In the public method MonthlyStrategy you try to give it a private class as a parameter Action<MonthlyStrategyDefaults> ... how the caller object would instantiate or deals with a private class! ... you have three solutions

  1. Change the accessibility for MonthlyStrategyDefaults and make it public
  2. Or you can configur based on base class, Action<DefaultsBase> instead of Action<MonthlyStrategyDefaults>
  3. Or make all configuration internally
  • Related