【问题标题】:How To Define A Flexible delegate field with multiple optional parameters?如何定义具有多个可选参数的灵活委托字段?
【发布时间】:2019-03-15 17:04:32
【问题描述】:

我正在开发一个模拟游戏,我在各种类中有一些条件方法,我想将它们用于随机的游戏内事件。

我的目标是创建一个用户友好的事件类,用户可以在其中通过 XML 序列化添加事件(这部分很好)。所以我试图让事情尽可能简单和通用。我在各种类中都有一些条件方法,例如

public class Person
{
    static bool IsOlderThan(int age) {/*...*/}
}

public class Faction
{
    static bool HasRelationMoreThan(Faction faction,float value) {/*...*/}
}

等等……

我必须定义一个 Func 参数或另一个可以接受这些具有不同参数范围的方法的委托,而不是为它们中的每一个定义不同的字段。 TL;DR:我需要一个接受任何方法作为值的委托类型。

有没有办法像这样创建灵活、通用的方法引用?

【问题讨论】:

  • 调用代理时会传递哪些参数?如果您只传递了 2 个参数但委托需要 3 个怎么办?
  • 我的意思是 any 数量的 any 参数:) 这就是我想知道的问题。
  • 你能展示一些使用这种机制的代码吗?你想写什么样的代码来使用这个“多个可选参数”的东西?
  • 恐怕没有太多选择:要么为您将要使用的每个参数组合定义单独的委托,要么定义将接受 Object 实例数组的委托可以放你的参数。
  • @Sweeper 我更新了我的问题并添加了一些示例来阐明我想要实现的目标。

标签: c# delegates func


【解决方案1】:

看看 MulticastDelegate 类。它是所有代表的基类。 不过要小心。 MulticastDelegates 是通过 DynamicInvoke() 调用的,它的工作速度比 Invoke() 慢。而且您还必须控制传递给 DynamicInvoke() 的参数的数量和类型,因为它可能导致运行时错误。

private void TestMulticastDelegate()
{
    Func<int, bool> function1 = IntToBool;
    Func<string, bool> function2 = StringToBool;
    Func<int, string, bool> function3 = IntAndStringToBool;

    int intArg = 1;
    string stringArg = "someString";

    MulticastDelegate d;

    d = new Func<int, bool>(IntToBool);
    bool res1 = d.DynamicInvoke(intArg).Equals(function1(intArg)); // always true

    d = new Func<string, bool>(StringToBool);
    bool res2 = d.DynamicInvoke(stringArg).Equals(function2(stringArg)); // always true

    d = new Func<int, string, bool>(IntAndStringToBool);
    bool res3 = d.DynamicInvoke(intArg, stringArg).Equals(function3(intArg, stringArg)); // always true
}

private bool IntToBool(int i)
{
    return i == 0;
}

private bool StringToBool(string s)
{
    return string.IsNullOrEmpty(s);
}

private bool IntAndStringToBool(int i, string s)
{
    return i.ToString().Equals(s, StringComparison.OrdinalIgnoreCase);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多