C# 如果一个方法有一个返回接口的类型,这意味着什么?

C# 如果一个方法有一个返回接口的类型,这意味着什么?,c#,C#,当我有这样的方法时: public IEnumerator<string> GetEnumerator() { foreach (string str in array) yield return str } public IEnumerator GetEnumerator() { foreach(数组中的字符串str) 收益率 } 方法“int”返回一个int 但是一个返回接口的方法意味着什么?接口只是一个通用的契约,说明返回的任何实际类型都可以执行x、y和z 考虑以下几点:

当我有这样的方法时:

public IEnumerator<string> GetEnumerator()
{
foreach (string str in array)
yield return str
}
public IEnumerator GetEnumerator()
{
foreach(数组中的字符串str)
收益率
}
方法“int”返回一个int


但是一个返回接口的方法意味着什么?

接口
只是一个通用的契约,说明返回的任何实际类型都可以执行x、y和z

考虑以下几点:

public interface IPerson
{
    string First { get; set; }
    string Last { get; set; }
}
然后,您可以有不同类型的实现(
联系人
员工
),但它们都有一个可以调用的
First
Last
属性

public interface Contact : IPerson
{
    public string First { get; set; }
    public string Last { get; set; }
    // Maybe other methods too
}


public interface Employee : IPerson
{
    public string First { get; set; }
    public string Last { get; set; }
    // Maybe other methods too
}
假设您有以下方法:

public IPerson GetPerson()
{
    var contact = new Contact();
    var employee = new Employee();

    // You can return either of these objects and the code that call it will be able to call the `First` and `Last` parameters.
}

在您的示例
IEnumerable
中,您可以枚举一些内容,例如
for(列表中的var项)

接口
只是一般契约,表示返回的任何实际类型都可以执行x、y和z

考虑以下几点:

public interface IPerson
{
    string First { get; set; }
    string Last { get; set; }
}
然后,您可以有不同类型的实现(
联系人
员工
),但它们都有一个可以调用的
First
Last
属性

public interface Contact : IPerson
{
    public string First { get; set; }
    public string Last { get; set; }
    // Maybe other methods too
}


public interface Employee : IPerson
{
    public string First { get; set; }
    public string Last { get; set; }
    // Maybe other methods too
}
假设您有以下方法:

public IPerson GetPerson()
{
    var contact = new Contact();
    var employee = new Employee();

    // You can return either of these objects and the code that call it will be able to call the `First` and `Last` parameters.
}
在您的示例中,
IEnumerable
可以枚举一些内容,例如
for(列表中的var项)

IEnumerable
对于
yield
关键字来说有点特殊。基本上,它意味着方法的返回类型是“可枚举的”,这意味着它是某种项目列表(在本例中为
string

这个方法与它是一个接口无关,神奇之处在于
yield
关键字

IEnumerable
对于
yield
关键字来说是一种特殊类型。基本上,它意味着方法的返回类型是“可枚举的”,这意味着它是某种项目列表(在本例中为
string

这个方法与它是一个接口无关,神奇之处在于
yield
关键字


从技术上讲,它不是返回接口,而是返回使用该接口的对象的实例。这是一个被称为的主题


多态性允许您返回派生自基类型或接口的类的不同实现。在代码中,您可以返回MyCollectionType或MyListType的实现(这两种类型都是可以创建以实现该接口的自定义集合类型),因为它们都实现了
IEnumerator
接口。

从技术上讲,它不返回接口,但它返回的是使用该接口的对象的实例。这是一个被称为的主题


多态性允许您返回派生自基类型或接口的类的不同实现。在代码中,可以返回MyCollectionType或MyListType的实现(这两种类型都是可以创建以实现该接口的自定义集合类型),因为它们都实现了
IEnumerator
接口。

用于枚举数(因此返回类型为
IEnumerator
),但一般来说,该函数将返回一个实现指定接口的对象。“str”然后立即实现该接口?这意味着该方法可以返回实现该接口的任何类型。用于枚举数(因此返回类型为
IEnumerator
),但通常该函数将返回实现指定接口的对象。“str”现在实现接口?这意味着该方法可以返回实现所述接口的任何类型。