Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

inheritance - Inject appropriate class C#

I need some advice on how to better structure my classes.

I have generic interface and class:

public interface IReader
{
        IEnumerable<Change> ReadChanges(string log, int count, string from);
}
public class Reader : IReader
    {
        private readonly MongoDb _db;

        public StageChangesReader(MongoDb db)
        {
            _db = db;
        }

        public IEnumerable<Change> ReadChanges(string log, int count, string from)
        {
             //....
        }
    }

Then I made three other classes that use this reader (they implement the same method and the only difference is log that I pas) something like this:

 public class SpecificReader
    {
        private readonly IReader _reader;

        public SpecificReader(IReader reader)
        {
            _reader = reader;
        }

        public IEnumerable<Change> ReadChanges(int count, string from)
        {
            return _changesReader.ReadChanges("specific log", count, from);
        }
    }

finally in the third class I want to inject these and based on the type use specific logging in the function:

var changes = _type == MyType.SpecificReader
                ? _specificReader.ReadSpecific(_count, from)
                : _somethingElse.ReadSomethingElse(_count, from);

I would like to make this more generic that instead of having if I could pass this one generic method.

so it would be like:

var changes = _Reader.ReadChanges(_count, from)

Is that possible?

question from:https://stackoverflow.com/questions/65935164/inject-appropriate-class-c-sharp

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

1 Answer

0 votes
by (71.8m points)

Considering adding a method in your interface and either overwriting it in your derived concrete classes, so you can call IConcreteClass.LogMethod() on all of them, making them responsible for the way they log.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...