无法创建抽象类或接口的实例 [英] Cannot create an instance of the abstract class or interface
问题描述
我有一个类和一个接口,当我尝试实例化接口时,我收到一个错误:
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.
但是,可以实例化实现该接口的类的实例(为其方法提供实现),在您的情况下是用户
类。
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();
这实例化用户
类的实例(提供实现),并将其分配给接口类型的对象变量( 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();
创建用户
类的实例并将其分配给相同类型的对象变量,但这种方法首先会破坏定义单独接口的目的。
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屋!