c# - 为什么我在实例化接口(interface)时出错?

标签 c# oop class interface instantiation

我有一个类和一个接口(interface),当我尝试实例化接口(interface)时,出现错误:

Cannot create an instance of the abstract class or interface

我的代码如下:

namespace MyNamespace
{
    public interface IUser
    {
        int Property1 { get; set; }
        string Property2 { get; set; }
        string Property3 { get; set; }
        void GetUser();
    }

    public class User : IUser
    {
        public int Property1 { get; set; }
        public string Property2 { get; set; }
        public string Property3 { get; set; }

        public void GetUser()
        {
           //some logic here...... 
        }

    }
}

当我尝试实例化 IUser user = new IUser(); 时出现错误:

Cannot create an instance of the abstract class or interface

我在这里做错了什么?

最佳答案

错误消息似乎不言自明。您无法实例化接口(interface)的实例,并且您已将 IUser 声明为接口(interface)。 (同样的规则适用于抽象类。)接口(interface)的全部意义在于它不任何事情——没有为其方法提供实现。

但是,您可以实例化一个实现该接口(interface)的类的实例(为其方法提供实现),在您的例子中是用户 类。

因此,您的代码需要如下所示:

IUser user = new User();

这会实例化 User 类(提供实现)的实例,并将其分配给接口(interface)类型的对象变量(IUser,它提供接口(interface),您作为程序员可以与对象交互的方式)。

当然你也可以这样写:

User user = new User();

它创建了 User 类的一个实例,并将其分配给相同类型的对象变量,但这首先违背了定义单独接口(interface)的目的。

关于c# - 为什么我在实例化接口(interface)时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6611412/

相关文章:

c# - 为什么不直接使用类字段呢?

c# - 从字符串数组中删除重复项

c++ - 将私有(private)方法类成员作为指向函数的指针传递

java - 生成方法中无法识别变量

javascript - 当修改一个类的一个实例的属性时,该类的所有实例的属性都会改变

c# - 如何从另一种方法访问我的控件

c# - iTextSharp for PDF - 如何添加文件附件?

c# - 多次调用 ToList 会影响性能吗?

java - Java 自定义注释有哪些合适的用途?

c++ - 在类访问混淆中声明的枚举类型