我有一个类和一个接口(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/