use*_*648 10 c# interface type-conversion
在C#中,如果我有参数类型是接口的函数的参数,那么如何传递实现接口的对象.
这是一个例子:
函数的参数如下:
List<ICustomRequired>
Run Code Online (Sandbox Code Playgroud)
我已经拥有的清单如下:
List<CustomObject> exampleList
Run Code Online (Sandbox Code Playgroud)
CustomObject继承自ICustomRequired接口
传递exampleList参数的正确语法是什么?
这就是我想要做的上述任务:
exampleList as List<ICustomRequired>
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
无法通过引用转换,装箱转换,取消装箱转换,换行转换或空类型转换来转换类型
谢谢
And*_*erd 14
您不能将List一种类型转换List为其他类型.
如果你考虑一下,你会很高兴你不能.想象一下,如果可能的话,你可能造成的破坏:
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
Run Code Online (Sandbox Code Playgroud)
但请注意,这行代码是合法的:
exampleList as IEnumerable<ICustomRequired>;
Run Code Online (Sandbox Code Playgroud)
这样做是安全的,因为IEnumerable它没有为您提供任何添加新对象的方法.
IEnumerable<T>实际上定义为IEnumerable<out t>,这意味着类型参数是Covariant.
你能把功能的参数改成IEnumerable<ICustomRequired>吗?
否则,您唯一的选择是创建一个新列表.
var newList = (exampleList as IEnumerable<ICustomRequired>).ToList();
Run Code Online (Sandbox Code Playgroud)
要么
var newList = exampleList.Cast<ICustomRequired>().ToList();
Run Code Online (Sandbox Code Playgroud)