【问题标题】:Use delegates in place of typedef in C#在 C# 中使用委托代替 typedef
【发布时间】:2014-05-05 08:01:59
【问题描述】:

在 C++ 中,我有以下代码:

class Card
{
    public:
        typedef void (*FunctType)(std::vector<Card> &KaibaHand, std::vector<Card> &KaibaDeck, std::vector< std::vector<Card> > &Field);   
    FunctType GetEffect();
    void SetEffect(FunctType setEffect);

private:
    FunctType Effect;
}

稍后在 Main() 函数中,我可以使用以下行调用 GetEffect

Card::FunctType effect = Field[0][TrapSlot-1].GetEffect();
(*effect) (KaibaHand, KaibaDeck, Field);

我不确定如何在 C# 中执行此操作。我读到了如何用 Degelates 替换函数指针。我在下面尝试但收到错误“找不到类型或命名空间名称'DelEffect'(您是否缺少 using 指令或程序集引用?)”

class Card
{
    void effect(List<Card> KaibaHand, List<Card> KaibaDeck, List< List<Card> > Field);   

public delegate void DelEffect(List<Card> KaibaHand, List<Card> KaibaDeck, List<List<Card>> Field);
    public void Effect
    {
        get { return effect; }
        set { effect = value; }
    }
}

在主函数中

DelEffect e1 = new DelEffect(Effect);

【问题讨论】:

    标签: c# c++ class delegates typedef


    【解决方案1】:

    您可以将Action&lt;&gt; 用于void 函数Func&lt;&gt; 当函数返回一个值

    // Action can be used as a shorter from of delegate 
    public Action<List<Card>, List<Card>, List<List<Card>>> Effect {
      get;
      set;
    }
    
    ...
    
    // Function
    private void effect(List<Card> KaibaHand, 
                        List<Card> KaibaDeck, 
                        List<List<Card>> Field) {
      ... 
    }
    
    ...
    
    Effect = effect;
    ...
    
    List<Card> KaibaHand = ... 
    List<Card> KaibaDeck = ...
    List<List<Card>> Field = ...
    
    // If function Effect is specified call it:
    if (!Object.ReferenceEquals(null, Effect)) {
      Effect(KaibaHand, KaibaDeck, Field);
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用Func<> DelegateAction<> Delegate(如果你的方法返回void):

      在你的情况下,它看起来像:

      class Card
      {
          public Action<List<Card>, List<Card>, List<Card>> Effect { get; set; }
      }  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-03
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多