如何在C#中返回带有各种参数的动态方法

时间:2017-11-23 12:42:50

标签: c# methods dynamic func

是否可以使用Func或任何类似的方法返回带有各种参数的动态方法

    public enum MethodType
    {
        T1,
        T2
    }
    Func<????, IRequest> MethodGenerator(MethodType methodType, Dictionary<Type, string> args)
    {
        switch (methodType)
        {
            case MethodType.T1:
                return Method1;
            case MethodType.T2:
                return Method2;
        }
        return null;
    }

    public IRequest Method1(string token, int state)
    {
        // Some Code
        return null;
    }
    public IRequest Method2(string token, int state, string name)
    {
        // Some Code
        return null;
    }
MethodGenerator(new Dictonary<type, string>(){MethodType.T1, {string, "token"},{int, "state"}}

最后一行返回 Method1

1 个答案:

答案 0 :(得分:0)

没有动态方式来表示Func的输入定义,而是您定义的类型可以是动态的。

给出以下对象:

public enum MethodType
{
    T1,
    T2
}

public class TestRequest
{
    public IRequest Method1(string token, int state)
    {
        // Some Code
        return new Request1();
    }
    public IRequest Method2(string token, int state, string name)
    {
        // Some Code
        return new Request2();
    }
}

public interface IRequest
{
    string RequestName();
}

public class Request1 : IRequest
{
    public string RequestName() => "Request1";
}

public class Request2 : IRequest
{
    public string RequestName() => "Request2";
}

然后您可以拥有以下课程:

public class TestClass
{
    private readonly Dictionary<MethodType, Func<object[], IRequest>> _definitions;

    public TestClass(Dictionary<MethodType, Func<object[], IRequest>> definitions)
    {
        _definitions = definitions;
    }

    public IRequest MethodGenerator(MethodType methodType,
        params object[] args)
    {
        return _definitions[methodType](args);
    }
}

我编写了以下测试来演示功能:

    [TestMethod]
    public void TestMethod1()
    {
        var definitions = new Dictionary<MethodType, Func<object[], IRequest>>
        {
            {
                MethodType.T1, objects =>
                {
                    var testRequest = new TestRequest();
                    return testRequest.Method1((string)objects[0], (int)objects[1]);
                }
            },
            {
                MethodType.T2, objects =>
                {
                    var testRequest = new TestRequest();
                    return testRequest.Method2((string)objects[0], (int)objects[1], (string)objects[2]);
                }
            }
        };

        var testClass = new TestClass(definitions);
        var result1 = testClass.MethodGenerator(MethodType.T1, "test", 1);
        var result2 = testClass.MethodGenerator(MethodType.T2, "test2", 1, "test2");

        Assert.AreEqual("Request1", result1.RequestName());
        Assert.AreEqual("Request2", result2.RequestName());
    }