C# - 使用ICollection 在通用属性而不是Collection中 [关闭]

问题描述 投票:-2回答:2

Collection<T>是一个类,ICollection<T>是一个接口。在MVC教程中我发现了这一点

public virtual ICollection<Enrollment> Enrollments { get; set; }

但是ICollection是一个界面,我不明白为什么会这样。实现通用属性的正确方法是这样的:

public MyProp<int> SomeProperty { get; set; }

所以,通过这个例子,它应该是这样的

public Collection<int> SomeProperty { get; set; }

ICollection是一个接口,因此它的实现应该是:

public class ClassName : ICollection<T>

我搜索了类似的问题,但我只找到了一个如何创建通用属性的示例

c# asp.net-mvc generics
2个回答
1
投票

这种方法完全有意义,因为类被设计为封装自己的底层实现。此外,Interfaces旨在标准化这种方法。要更好地理解它,请考虑IEnumarable<T>界面。如果在任何类设计上实现此接口,则您的类将自动变为可枚举(这意味着它可以与foreach一起使用)。

在您的情况下,它返回qazxsw poi,因为他们希望您使用标准化的接口方法。

如果您编写以下代码

ICollection<T>

注册变量将自动视为以下内容

var enrollment = myObj.Enrollments 

这种方法促使您编写具有更好设计的模块化代码,因为您最终使用标准化接口调用。

在每种情况下,您有时需要创建例外。如果出现类似的内容,您基本上可以使用要转换为的类型,如下所示。

ICollection<Enrollment> enrollment = myObj.Enrollments

通过这种方法,您可以访问来自Collection<Enrollment> enrollment = myObj.Enrollments 类的所有公共方法


0
投票

实现泛型接口的类本身就是通用的,这是完全正常的。例如,Collection<T>实现List<T>

或者,例如,

IList<T>

可以在类级别或方法级别声明泛型类型参数。例如,您可以这样做:

public interface IDoesSomethingWith<T>
{
    void DoSomethingWith(T theThing);
}

public class DoesSomethingWith<T> : IDoesSomethingWith<T>
{
    public void DoSomethingWith(T theThing)
    {
        throw new NotImplementedException();
    }
}

泛型接口(或从泛型类继承的类)的实现可以指定具体类型,而不是通用本身。

在此示例中,接口是通用的,但实现它的类不是。

public class DoesSomethingWith<T> : IDoesSomethingWith<T>
{
    public void DoSomethingWith(T theThing)
    {
        // uses generic type of class
    }

    public void DoSomethingWith<TAnotherThing>(TAnotherThing anotherThing)
    {
        // uses generic type of method
    }

    public void DoSomethingWith<TAnotherThing>(T thing, TAnotherThing anotherThing)
    {
        // uses generic type of class and method
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.