如何使用多个可选参数定义灵活的委托字段?

问题描述 投票:1回答:1

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

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

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

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

等等...

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

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

c# delegates func
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.