为什么在实例化接口时出现错误? [英] Why do I get an error instantiating an interface?

查看:94
本文介绍了为什么在实例化接口时出现错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class and an interface, and when I try to instantiate the interface, I get an error:

无法创建抽象类或接口的实例

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();时,我得到一个错误:

When I try to instantiate IUser user = new IUser(); I get an error:

无法创建抽象类或接口的实例

Cannot create an instance of the abstract class or interface

我在做什么错了?

推荐答案

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

The error message seems self-explanatory. You can't instantiate an instance of an interface, and you've declared IUser as an interface. (The same rule applies to abstract classes.) The whole point of an interface is that it doesn't do anything—there is no implementation provided for its methods.

但是,您可以 实例化一个实现接口(提供其方法的实现)的类的实例,在您的情况下,该实例是User

However, you can instantiate an instance of a class that implements that interface (provides an implementation for its methods), which in your case is the User class.

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

Thus, your code needs to look like this:

IUser user = new User();

这将实例化User类的一个实例(提供实现),并将其分配给接口类型的对象变量(IUser,该变量提供接口,作为程序员,您可以使用该方法与对象互动).

This instantiates an instance of the User class (which provides the implementation), and assigns it to an object variable for the interface type (IUser, which provides the interface, the way in which you as the programmer can interact with the object).

当然,您也可以这样写:

Of course, you could also write:

User user = new User();

创建User类的实例并将其分配给相同类型的对象变量,但这种做法违背了首先定义单独接口的目的.

which creates an instance of the User class and assigns it to an object variable of the same type, but that sort of defeats the purpose of a defining a separate interface in the first place.

这篇关于为什么在实例化接口时出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆