You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何声明存储实现IInterface接口的类引用的列表?

嘿,这问题我熟!咱们分两种场景来给你讲清楚,完全匹配你的需求👇

场景1:存储接口实现类的实例(最常用、最直接的方案)

如果你的myClass、myClass2是已经创建好的对象实例,那直接用List<IInterface>声明列表就搞定了!因为所有实现IInterface的类的实例,都能隐式转换为IInterface类型,编译器会自动识别这些实例具备接口的所有成员,后续调用完全不用额外转换:

// 直接用接口类型作为列表的泛型参数
List<IInterface> references = new List<IInterface> 
{ 
    new MyClass(), 
    new MyClass2(), 
    new MyClass3() 
};

// 后续使用时,直接调用接口方法,编译器完全知晓类型
foreach (var item in references)
{
    item.YourInterfaceMethod(); // 毫无压力,编译器知道item实现了IInterface
}

场景2:存储接口实现类的类型本身(对应你给出的List示例)

如果你想存储的是类的类型(比如MyClass、MyClass2这些Type对象,而非实例),同时希望编译器在创建实例时自动识别这些类型实现了IInterface,有两种靠谱方案:

方案A:List + 反射创建实例(简单直接)

虽然声明List<Type>时编译器没法直接约束元素都实现IInterface,但你可以在添加元素时自行保证,创建实例时直接转为IInterface类型,编译器就能识别了:

List<Type> interfaceTypes = new List<Type> 
{ 
    typeof(MyClass), 
    typeof(MyClass2), 
    typeof(MyClass3) 
};

// 创建实例并安全转为接口类型
foreach (var type in interfaceTypes)
{
    // 可选:提前检查类型是否实现接口,避免运行时错误
    if (typeof(IInterface).IsAssignableFrom(type))
    {
        IInterface instance = (IInterface)Activator.CreateInstance(type);
        instance.YourInterfaceMethod(); // 编译器明确知道instance是IInterface类型
    }
}

方案B:自定义泛型集合(编译阶段强约束)

如果想在编译时就拦截掉未实现IInterface的类型,避免后期运行时出错,可以自己写一个带泛型约束的集合类:

public class InterfaceTypeList<TInterface> : List<Type> where TInterface : class
{
    // 重写Add方法,只允许添加实现了TInterface的类型
    public new void Add<T>() where T : TInterface
    {
        base.Add(typeof(T));
    }
}

// 使用方式:
InterfaceTypeList<IInterface> interfaceTypes = new InterfaceTypeList<IInterface>();
interfaceTypes.Add<MyClass>();
interfaceTypes.Add<MyClass2>();
interfaceTypes.Add<MyClass3>();
// 这里如果尝试添加未实现IInterface的类,编译时直接报错!

// 创建实例时:
foreach (var type in interfaceTypes)
{
    IInterface instance = (IInterface)Activator.CreateInstance(type);
    instance.YourInterfaceMethod();
}

这种方案的优势是从源头避免错误,所有不符合要求的类型在编译阶段就会被拦截。


内容的提问来源于stack exchange,提问作者Azeranth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:14:54