无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换来转换类型 [英] Cannot convert type via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
问题描述
在 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>
我已有的列表如下:
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>
但是我收到以下错误:
无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换
Cannot convert type via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion
谢谢
推荐答案
您不能将一种类型的 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
实际上定义为IEnumerable
,表示类型参数为协变.
IEnumerable<T>
is actually defined as IEnumerable<out t>
, which means the type parameter is Covariant.
能不能把函数的参数改成IEnumerable
?
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();
这篇关于无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换来转换类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!