这个问题在这里已经有了答案:
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;
var menuItems = new MenuItems();
var result = _instance.GetMenuItem<MenuItem1>() as IMenuItem;
关于c# - 如何将泛型函数存储在c#中的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59266362/