简体   繁体   中英

Creating delegates to pass to base class constructor in constructor of derived class

I have a class DerivedClass which extends BaseClass. BaseClass has a constructor that takes two delegates and string that looks as so:

public BaseClass(Func<string, bool> stringToBool, Func<string, string> stringToString)
{
    ... 
}

In DerivedClass, I want to have a default constructor which calls the base constructor, passing in delegates that work in a simple, 'default' manner, eg stringToBool always returns false, or stringToString always returns the string that is passed to it. How can I accomplish this?

class BaseClass
{
    public BaseClass(Func<string, bool> stringToBool, Func<string, string> stringToStirng)
    {

    }
}


class DerivedClass : BaseClass
{
    public DerivedClass() : base(s => true, s => s)
    {

    }
}

Based on your use of the phrase "default manner" I believe this is what you actually want then:

public class BaseClass {
    public BaseClass(
        Func<string, bool> stringToBool = null,
        Func<string, string> stringToString = null
    ){
        stringToBool = stringToBool ?? DefaultStringToBool;
        stringToString = stringToString ?? DefaultStringToString;
    }

    private static bool DefaultStringToBool(string s) {
        <Insert default logic here>;
    }

    private static string DefaultStringToString(string s) {
        <Insert default logic here>;
    }
}

Then you don't even need to touch constructor base stuff at all unless you want to override that default logic.

However, you really shouldn't be doing this at all, it tightly couples your classes.

Better to just do this:

public abstract class BaseClass {

    protected virtual bool DefaultStringToBool(string s) {
        <Insert default logic here>;
    }

    protected virtual string DefaultStringToString(string s) {
        <Insert default logic here>;
    }
}

public DerivedClass : BaseClass {
    protected override string DefaultStringToString(string s) {
        <Insert override logic here>;
    }
}

There's a design flaw in your system if you are passing Funcs into your instantiation methods, since classes already can have overridable methods, abstract methods, virtual methods, etc.

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