c# - 如何将泛型函数存储在c#中的变量中?

标签 c# .net generics asp.net-core .net-core

这个问题在这里已经有了答案:





What is the purpose of new() while declaration of a generic class?

(7 个回答)


12 个月前关闭。




我有以下代码:

public interface IMenuItem
{
    IWebElement Parent { get; }
}
public class MenuItems
{
    public T GetMenuItem<T>() where T : IMenuItem, new()
    {
        var menuItem = new T();

        return menuItem;
    }
}
public abstract class Page : IEnumerable<IComponent>
{
    private Func<IMenuItem> _getMenuItems = new MenuItems().GetMenuItem<IMenuItem>;
}

我正在尝试存储 new MenuItems().GetMenuItem<IMenuItem> _getMenuItems中的函数字段,但由于这是一个通用函数,所以它不起作用。如何将泛型函数存储到变量中?

new MenuItems().GetMenuItem<IMenuItem>不起作用,它告诉我:

'IMenuItem' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MenuItems.GetMenuItem()'



现在我有许多实现 IMenuItem 的具体类型我希望代表接受这些。我不想为每个实现 IMenuItem 的具体类型创建一个单独的委托(delegate)。 .相反,我有一个可以接受实现 IMenuItem 的具体类型的委托(delegate)。 .

最佳答案

问题在于 new()约束。

The new constraint specifies that a type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.



由于IMenuItem是一个接口(interface),它不能被实例化,因此 new()约束将是一个问题。

编辑:

您可以通过以下几种方式解决此问题:
  • 您可以使用反射来检索方法并调用它:
    var method = typeof(MenuItems).GetMethod("GetMenuItem");
    var instance = new MenuItems(); // Maybe convert the class into a static class??
    var genericMethod = method.MakeGenericMethod(typeof(MenuItem1));
    var result = genericMethod.Invoke(instance, null) as IMenuItem;
    
  • 使用动态调用它:
    dynamic instance = new MenuItems(); // Maybe convert the class into a static class??
    var result = instance.GetMenuItem<MenuItem1>() as IMenuItem;
    
  • 持有 MenuItems 的实例而不是方法本身:
    var menuItems = new MenuItems();
    var result = _instance.GetMenuItem<MenuItem1>() as IMenuItem;
    
  • 关于c# - 如何将泛型函数存储在c#中的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266362/

    相关文章:

    c# - 连续执行的多线程 WebRequests

    c# - Google Analytics API fromdate,todate。如何从开始跟踪时开始?

    c# - 从 Application UnhandledException 事件中的 StackTrace 获取方法、类和行号

    java - Java 中用特定类代替泛型

    java - 实现两个接口(interface)的变量

    c# - 自动映射器。如果源成员为空则映射

    c# - 使用csc时出现奇怪的警告

    c# - 在库中使用 .Net Standard 1.4 并在应用程序中使用 .Net framework 4.6.1 时,无法加载文件 System.IO.FileSystem,Version=4.0.1.0

    c# - 重新启动(回收)应用程序池

    带有泛型的 Swift 枚举值