繁体   English   中英

我可以在同一个类的另一个委托中访问委托吗?

[英]Can I access delegate inside another delegate of same class?

我不知道我的理解是否有误,但是我正在尝试执行以下操作:

我有两个代表的基类:

 public class Base
 {
     public Func<bool> Licensed { get; set; }
     public Func<bool> Enabled { get; set; }
 }    

并派生一个类,如下所示:

public class Derived : Base
{
    public int Test { get; set; }
}

现在,我试图在Main():实例化派生类Main():

static void Main(string[] args)
{
    Derived obj = new Derived()
    {
        Licensed = () => { return true; },
        Enabled = () => { return Licensed() && true; }, //access above delegate
     };
}

事情是在Enabled实现中,我想访问刚刚分配的Licensed委托。 我无法实现此目标,因为这是不允许的。 这可以通过其他方式实现吗?

您不能在对象初始化程序中引用其他属性。 C#语言规范7.6.10.2对象初始化程序:

对象初始化程序不可能引用正在初始化的新创建的对象。

但是您可以使用老式的属性分配:

var obj = new Derived { Licensed = () => true; };
obj.Enabled = () => obj.Licensed() && true;

注意 :我提供此答案是为了向OP显示解决问题的其他方法。 我不会说不,您无法提供完整的解释,因为@SergeyBerezovskiy已经回答了这个问题

另一个选择是将其转换为流利的API

当我需要设置代表时,我倾向于认为它们应该设置一次,永远不要改变 因此,持有这些代表的属性应该是公共可读的并且可以私有设置。

另一方面,应使用工厂方法创建流畅配置的对象,并且其构造函数将为private

最后,流畅链上的每个方法还应该注入正在配置的实例,而您最终将设置一个委托,该委托调用作为参数传递给配置方法的委托。

也就是说,您以非常优雅的方式获得了想要的东西。

public class Derived : Base
{
     private Derived() {}

     public static Derived Create() => new Derived();

     public Func<bool> Licensed { get; private set; }
     public Func<bool> Enabled { get; private set; }

     public void LicensedIf(Func<Derived, bool> licensingCondition)
            => Licensed = () => licensingCondition(this);

     public void EnabledIf(Func<Derived, bool> enablingCondition)
            => Enabled = () => enablingCondition(this);
}

// Fluent configuration of your *licensable object* gets self-documented
// by the usage!
// Oh, and see how EnableIf() takes advantage of C#6's null conditional
// operator to invoke the "Licensed" delegate if its really set. This is
// so safe!
var derived = Derived.Create().LicenseIf(d => true)
                              .EnableIf(d => d.Licensed?.Invoke() && true);

在函数编程中将委托封装在委托中的事情称为currying 请参阅什么是“固化”? 如果您对此主题感兴趣。

暂无
暂无

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

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