简体   繁体   English

如何正确实现接口成员?

[英]How to implement an interface member correctly?

I am coding a simple application that works with collections. 我正在编写一个适用于集合的简单应用程序。 How do I properly implement an interface method in the case below? 在以下情况下,如何正确实现接口方法? Currently, it shows an error "not all code paths return a value". 当前,它显示错误“并非所有代码路径都返回值”。

This is my home task. 这是我的家庭任务。 The class "Time" is already implemented and works properly. 类“时间”已经实现并且可以正常工作。 I tried to find any examples of successful implementation of this method on the Internet but failed. 我试图找到在Internet上成功实施此方法的任何示例,但均失败了。

class MyCollection : ICollection<Time> 
    {
        List<Time> arr = new List<Time>();

        int ICollection<Time>.Count
        {

            get
            {
                arr.Count();
            }    
        }
     }

I am getting an error: 我收到一个错误:

CS0161 "MyCollection.ICollection.Count.get': not all code paths return a value" CS0161“ MyCollection.ICollection.Count.get':并非所有代码路径都返回值”

You are missing a return statement on your getter . 您在getter上缺少return声明。

class MyCollection : ICollection<Time> 
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count
    {

        get
        {
            return arr.Count();
        }    
    }
 }

Also, you can use Expression body definition => 另外,您可以使用表达式主体定义 =>

class MyCollection : ICollection<Time>
{
    List<Time> arr = new List<Time>();

    int ICollection<Time>.Count => arr.Count;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM