简体   繁体   中英

Call base constructor with method as argument

I am a beginner in C# and cannot find out how to call a base constructor from within a subclass:

Base class:

public class LookupScript
{
    protected Func<IEnumerable> getItems;

    protected LookupScript()
    {
        //
    }

    public LookupScript(Func<IEnumerable> getItems) : this()
    {
        Check.NotNull(getItems, "getItems");
        this.getItems = getItems;
    }

My derived class:

public class PresenceLookup : LookupScript
{
    public PresenceLookup() :base(??)
    {
     //
    }
    List<string> myMethod()
    {
        return null;
    }

How can I pass myMethod to the base class?

Thank you

You can't, as myMethod is an instance method, and you can't access anything to do with the instance being created within the constructor initializer. This would work though:

public class PresenceLookup : LookupScript
{
    public PresenceLookup() : base(MyMethod)
    {
    }

    private static List<string> MyMethod()
    {
        return null;
    }
}

That uses a method group conversion to create a Func<List<string>> that will call MyMethod .

Or if you don't need the method for anything else, just use a lambda expression:

public class PresenceLookup : LookupScript
{
    public PresenceLookup() : base(() => null)
    {
    }
}

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