创建具有不同参数类型的C#Func列表

c#

我希望能够创建多个Funcs,每个 s 接受一个类型的实例并返回相同的类型,例如:

Func<Foo, Foo>
Func<Bar, Bar>

然后将这些添加到 a List(或者可能添加到 a Dictionary,由Func处理的类型键控)。

然后给定任何实例y(其类型在编译时未知),我想检索并调用Func适用于 on 的实例y

我所要求的甚至可能吗?

回答

您可以创建一个代表字典。使用类型作为键。

Dictionary<Type, Delegate> _dictionary = new();

我们需要一个方法来添加委托:

bool Add<T>(Func<T, T> func)
{
    return _dictionary.TryAdd(typeof(T), func);
}

还有一个叫他们:

static T DoIt<T>(T t)
{
    if (_dictionary.TryGetValue(typeof(T), out var func))
    {
        return ((Func<T, T>)func).Invoke(t);
    }
   
    throw new NotImplementedException();
}

工作示例:

using System;
using System.Collections.Generic;
                    
public class Program
{
    private static Dictionary<Type, Delegate> _dictionary = new();
    
    public static void Main()
    {      
        Add<String>(InternalDoIt);
        Add<int>(InternalDoIt);
        DoIt("Hello World"); // Outputs "Hello World"
        DoIt(1); // Outputs "1"
        DoIt(DateTime.Now); // Throws NotImplementException
    }
    
    static bool Add<T>(Func<T, T> func)
    {
        return _dictionary.TryAdd(typeof(T), func);
    }
    
    static T DoIt<T>(T t)
    {
        if (_dictionary.TryGetValue(typeof(T), out var func))
        {
            return ((Func<T, T>)func).Invoke(t);
        }
        
        throw new NotImplementedException();
    }
    
    static string InternalDoIt(string str){
            Console.WriteLine(str);
            return str;
    }
    static int InternalDoIt(int i) {
            Console.WriteLine(i);
            return i;
    }
}

在这个答案的制作过程中没有小狗或小猫死亡。


以上是创建具有不同参数类型的C#Func列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>