从泛型类调用委托方法

时间:2019-06-11 21:31:36

标签: c# class generics delegates

我想从SomeClass调用MyDelegateMethod,但是我不知道该怎么做。我希望我的班级能为每个代表工作,而不仅仅是示例代码中提供的那个人。

谢谢!

using System;

namespace SomeTest
{
    public class Program
    {
        public delegate int MyDelegate(string str);
        public static int MyDelegateMethod(string str) => str.Length;

        public static void Main(string[] args)
        {
            var test = new SomeClass<MyDelegate>(MyDelegateMethod);
            test.Test();

        } 
    }

    public class SomeClass<SomeDelegate> where SomeDelegate : class
    {
        SomeDelegate MyDelegateMethod;

        public SomeClass(SomeDelegate MyDelegateMethod) => this.MyDelegateMethod = MyDelegateMethod;
                                             /* this part of code fails */
        public void Test() => Console.WriteLine(MyDelegateMethod("Test"));
    }
}

1 个答案:

答案 0 :(得分:1)

在特殊情况下,您提供的您可以使用Func<string, int>代替这样的委托:

public class Program
{

    public static int MyDelegateMethod(string str) => str.Length;

    public static void Main(string[] args)
    {
        var test = new SomeClass(MyDelegateMethod);
        test.Test();

    }
}

public class SomeClass
{
    Func<string, int> MyDelegateMethod;

    public SomeClass(Func<string, int> MyDelegateMethod) => this.MyDelegateMethod = MyDelegateMethod;

    public void Test() => Console.WriteLine(MyDelegateMethod("Test"));
}

您可以将其概括为任何单个输入/单个输出函数,如下所示:

public class Program
{

    public static int MyDelegateMethod(string str) => str.Length;

    public static void Main(string[] args)
    {
        var test = new SomeClass<string, int>(MyDelegateMethod);
        test.Test("Test");

    }
}

public class SomeClass<TIn, TOut>
{
    Func<TIn, TOut> MyDelegateMethod;

    public SomeClass(Func<TIn, TOut> MyDelegateMethod) => this.MyDelegateMethod = MyDelegateMethod;

    public void Test(TIn input) => Console.WriteLine(MyDelegateMethod(input));
}