c# - 如何将“类列表”转换为“其接口列表”?
问题描述
我需要将一个类列表转换为它自己的接口列表。
所以我有接口Demo_Interface
和两个基于的类Demo_Interface
,现在我创建类列表,如List<Test_Class1>
我有一个带List<Demo_Interface>
参数的函数。
这是界面:
interface Demo_Interface
{
int test_int { get; set; }
}
这是整个代码:
using System;
using System.Collections.Generic;
namespace ConsoleApp3
{
class Program
{
///// Main Interface
interface Demo_Interface
{
int test_int { get; set; }
}
//// Class 1 Based On Demo_Interface
class Test_Class1 : Demo_Interface
{
public int test_int { get; set; }
public string test_string { get; set; }
}
///// Class 2 Based On Demo_Interface
class Test_Class2 : Demo_Interface
{
public int test_int { get; set; }
public string test_string { get; set; }
}
//// And Main Class
class Main_Class
{
public List<Test_Class1> class_list_1 { get; set; }
public List<Test_Class2> class_list_2 { get; set; }
public Main_Class()
{
class_list_1 = new List<Test_Class1>() { };
class_list_2 = new List<Test_Class2>() { };
}
}
//// Console Main
static void Main(string[] args)
{
var new_main_class = new Main_Class();
Output_Class(new_main_class.class_list_1); ///// ==> ERROR
Console.ReadKey();
}
//// Simple Function for do something with interface
static void Output_Class(List<Demo_Interface> inter_input)
{
for (int i = 0; i < inter_input.Count; i++)
{
Console.WriteLine("{0} - {1}",i, inter_input[i].test_int);
}
}
}
}
当Test_Class1使用Demo_InterfaceList<Test_Class1>
时,我该如何转换?List<Demo_Interface>
解决方案
您不能将 a 转换List<ClassThatImplementsInterface>
为List<IInterfaceItImplements>
.
如果可以,并且您这样做了:
var classList = new List<ClassThatImplementsInterface>();
var interfaceList = (List<IInterfaceItImplements>)classList;
...那么你就可以做到这一点:
interfaceList.Add(new SomeOtherClassThatImplementsTheInterface);
但是投射列表不会创建新列表。在上面的示例中,没有两个列表。有两个变量引用了同一个列表。如果您可以如上所示进行强制转换,您将能够定义一种类型的列表并为其添加完全不同的类型。编译器会阻止这种情况。
你可以
- 创建一个新
List<IDemoInterface>
的并将项目添加到其中。(或数组、IEnumerable 等) - 将列表保持原样,并在需要时/如果需要时投射单个项目。在大多数情况下,我们不需要将某些东西转换为它实现的接口。
如果我们需要将整个集合转换为不同的类型,很可能是因为我们将它作为参数传递。
这实际上是不将方法参数定义为List<T>
可以修改的集合类型的一个很好的理由,除非我们打算修改集合。
这就是我们传递不太具体的集合类型的原因之一,比如IEnumerable<T>
.
假设方法参数如下所示:
void MethodINeedToPassTheArgumentTo(IEnumerable<IDemoInterface> items)
现在我们可以使用我们的List<TestClass>
并执行以下操作:
MethodINeedToPassTheArgumentTo(testClassList.Cast<IDemoInterface>);
我们不会创建一个新的集合。我们正在传递一个引用,该引用允许其他方法查看列表中的项目,每个项目都单独转换为IDemoInterface
. 出于实际目的,它看起来像集合的其他方法IDemoInterface
,这没关系,因为其他项目不能修改集合。它不能尝试将其他类型添加到List<TestClass>
.
推荐阅读
- stata - 面板数据中每个国家的描述性统计
- php - Laravel - Vue.js 路由无法正常工作
- c - 可以将套接字作为 const 传递给函数吗?
- javascript - How to know index of DataTable row just added?
- sql - 找到预期的 END B1 验证配置
- c++ - 空白程序在 Windows 中链接时不退出
- awk - grep 与 min 匹配数
- xamarin.forms - Xamarin Forms iOS 应用 MsalClientException(TeamId 为空)
- magento2 - 更改 getPdf 函数
- c# - 有没有办法对连接到 Azure SignalR 的用户进行身份验证?