c# - 无法为接口(interface)添加约束

标签 c# interface constraints

我有这个界面:

namespace Common.Extensions
{
    public interface IExtension
    {
        string FriendlyName { get; }
        string Description { get; }
    }
}

在其他类方法中,我有这样的定义:

public void LoadExtensions<T>(T tipo) where T : Common.Extensions.IExtension
{

}

在那个方法的内部,我有这个:

T extension = Activator.CreateInstance(t) as T;

其中“t”是从 DLL 动态加载的类型。该类型实现 IExtension 接口(interface)。

使用该代码,我收到此编译时错误:

The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint

根据文档,我尝试做的是有效的。这里缺少什么?

杰米

最佳答案

as 运算符只能用于引用类型或可空类型 ( reference )。如果接口(interface)由结构 as 实现,将无法使用它。

您可以将 T 限制为一个类

public void LoadExtensions(T tipo) where T : class, Common.Extensions.IExtension

或者您可以使用常规转换:

T extension = (T)Activator.CreateInstance(t);

注意

您还可以向方法添加 new() 约束以强制 T 具有默认构造函数以避免运行时问题,并且根本不使用强制转换:

public static void LoadExtensions<T>(T tipo) where T : IExtension, new()
{
    T extension = new T();
}

关于c# - 无法为接口(interface)添加约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49112122/

相关文章:

php - SQLSTATE[23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails - Laravel

c# - 可观察对象/动态接口(interface)?

Java-未找到通用类型?

java - 多态性和接口(interface) - 澄清?

constraints - 最小独立集

swift - UIImage 大于约束尺寸

c# - 如何在 xaml 中应用多个数据上下文?

c# - 创建 https 操作链接

C# 对整数的操作

oop - 接口(interface)的功能主要是为了使用函数而不知道类是如何构建的吗?