gpt4 book ai didi

c# - 如何将 Collection 作为 Collection 返回?

转载 作者:行者123 更新时间:2023-11-30 19:14:10 25 4
gpt4 key购买 nike

我有一个具体类,其中包含另一个具体类的集合。我想通过接口(interface)公开这两个类,但我无法弄清楚如何将 Collection 成员公开为 Collection 成员。

我目前使用的是 .NET 2.0

下面的代码会导致编译错误:

Cannot implicitly convert type 'System.Collections.ObjectModel.Collection<Nail>' to 'System.Collections.ObjectModel.Collection<INail>'

注释的强制转换尝试给出了这个编译器错误:

Cannot convert type 'System.Collections.ObjectModel.Collection<Nail>' to
'System.Collections.ObjectModel.Collection<INail>' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion.

有什么方法可以将具体类型的集合公开为接口(interface)的集合,还是需要在接口(interface)的getter方法中创建一个新的集合?

using System.Collections.ObjectModel;

public interface IBucket
{
Collection<INail> Nails
{
get;
}
}

public interface INail
{
}

internal sealed class Nail : INail
{
}

internal sealed class Bucket : IBucket
{
private Collection<Nail> nails;

Collection<INail> IBucket.Nails
{
get
{
//return (nails as Collection<INail>);
return nails;
}
}

public Bucket()
{
this.nails = new Collection<Nail>();
}
}

最佳答案

C# 3.0 泛型是不变的。如果不创建新对象,您将无法做到这一点。 C# 4.0 引入了安全协变/逆变,它无论如何都不会改变读/写集合(您的情况)的任何内容。

关于c# - 如何将 Collection<ConcreteType> 作为 Collection<Interface> 返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1332084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com