将列表接口强制转换为自定义列表类



我目前有一个自定义类,可以扩展和IList。

public class CustomList<T> : IList<T>
{
}

现在在我的代码中的某个地方我有这个

IList<string> _myList = new CustomList<string>();

我的问题是如何将_myList转换为自定义列表?

您可以尝试 C# 7 功能,即模式匹配,

喜欢

if(_myList is CustomList<string> customList)
{
//Your code 
}

如@TanvirArjel建议的那样,C#6 及更低版本支持的显式类型转换

CustomList<string> customList = (CustomList<string>)_myList; 

最新更新