c# - Declare a List of class references
问题描述
I need to declare a list of class references. Specifically, a list of classes which implement a interface which here I'll call IInterface
.
Similar to how List can be a list of types and look like this:
List<Type> types = new List<Type> {string, bool, int, float};
I need to accomplish the same thing, where each of those are my own classes and implement the interface IInterface so:
List<(idk)> references = new List<(idk)> {myClass, myClass2, myClass3};
and all of them are MyClass : IInterface
, MyClass2 : IInterface
and MyClass3 : IInterface
.
I need this so that when I create and instance of the type, the compiler will know that the type implements IInterface
.
解决方案
如果您基本上想要一个List<Type>
需要Type
s 来实现接口的地方,并且您希望在编译时强制执行,这实际上可以通过包装List<Type>
并使 add 方法具有受约束的泛型类型参数并使用它添加到列表中,但使用起来可能有点笨拙(您将无法使用您在问题中提到的漂亮的集合初始值设定项语法):
public class TypeList<T> : IEnumerable<Type>
{
private List<Type> _list = new List<Type>();
public void Add<TAdd>() where TAdd : T
{
_list.Add(typeof(TAdd));
}
public IEnumerator<Type> GetEnumerator() => _list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator();
}
此类的泛型类型参数是您希望列表约束的类型,因此在您的示例中,使用列表如下所示:
var list = new TypeList<IInterface>();
list.Add<MyClass>();
list.Add<MyClass2>();
list.Add<MyClass3>();
这些将无法编译:
list.Add<string>();
list.Add<bool>();
list.Add<int>();
list.Add<float>();
推荐阅读
- ffmpeg - 使用 ffmpeg 检测视频文件中的相同场景
- r - 将文件名附加到R中的数据框
- python - 在 elif 语句说这样做之后,我的变量没有改变
- r - 在R中制作2位数的月份和日期列
- c++ - 我想将以下行存储到 C++ 中的字符串数组中。我该怎么做?
- python-3.x - 在 BeeWare 上创建公文包时出错
- php - 如何同时使用 SQL COUNT 和 mysqli_stmt_num_rows?
- laravel - Laravel:由于添加了中间件,功能测试失败
- python-pptx - 在 python-pptx 中将项目符号添加到文本占位符中
- hugo - 如何设置HUGO.io登陆页面?