简体   繁体   English

使用方法作为参数调用基础构造函数

[英]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: 我是C#的初学者,无法从子类中找到如何调用基础构造函数:

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? 如何将myMethod传递给基类?

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. 您不能,因为myMethod是一个实例方法,并且您无法访问与构造函数初始值设定项中创建的实例有关的任何内容。 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 . 它使用方法组转换来创建将调用MyMethodFunc<List<string>>

Or if you don't need the method for anything else, just use a lambda expression: 或者,如果您不需要其他任何方法,只需使用lambda表达式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM