问题描述
在C#中,如果我有一个参数类型为接口的函数的参数,那么如何传递实现该接口的对象.
In C#, if I have a parameter for a function where the parameter type is of an interface, how do a pass in an object that implements the interface.
这里是一个例子:
函数的参数如下:
List<ICustomRequired>
我已经拥有的列表如下:
The list that I already have is as follows:
List<CustomObject> exampleList
CustomObject
从ICustomRequired
接口继承
将exampleList
作为参数传递的正确语法是什么?
What is the correct syntax to pass the exampleList
as a parameter?
这就是我认为完成上述任务的方式:
This is how I thought to do the above task:
exampleList as List<ICustomRequired>
但是我遇到以下错误:
谢谢
推荐答案
您不能将一种类型的List
强制转换为另一种类型的List
.
You cannot cast a List
of one type to a List
of a different type.
如果您考虑一下,您将很高兴不会这样做.想象一下,如果可能的话,可能造成的破坏:
And if you think about it, you would be glad that you can't. Imagine the havoc you could cause if it was possible:
interface ICustomRequired
{
}
class ImplementationOne : ICustomRequired
{
}
class ImplementationTwo: ICustomRequired
{
}
var listOne = new List<ImplementationOne>();
var castReference = listOne as List<ICustomRequired>();
// Because you did a cast, the two instances would point
// to the same in-memory object
// Now I can do this....
castReference.Add(new ImplementationTwo());
// listOne was constructed as a list of ImplementationOne objects,
// but I just managed to insert an object of a different type
但是请注意,以下代码行是合法的:
Note, however, that this line of code is legal:
exampleList as IEnumerable<ICustomRequired>;
这是安全的,因为IEnumerable
不会为您提供任何添加新对象的方法.
This would be safe, because IEnumerable
does not provide you with any means to add new objects.
IEnumerable<T>
实际上定义为IEnumerable<out t>
,这意味着类型参数为.
IEnumerable<T>
is actually defined as IEnumerable<out t>
, which means the type parameter is Covariant.
您是否可以将函数的参数更改为IEnumerable<ICustomRequired>
?
Are you able to change the parameter of the function to IEnumerable<ICustomRequired>
?
否则,您唯一的选择是创建一个新列表.
Otherwise your only option will be to create a new List.
var newList = (exampleList as IEnumerable<ICustomRequired>).ToList();
或
var newList = exampleList.Cast<ICustomRequired>().ToList();
这篇关于无法通过引用转换,装箱转换,拆箱转换,换行转换或空类型转换来转换类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!