如何在C#中向接口添加成员变量
我知道这可能是基本的,但我似乎无法向接口添加成员变量。 我尝试将接口继承到抽象类并向抽象类添加成员变量,但它仍然不起作用。这是我的代码:
public interface IBase {
void AddData();
void DeleteData();
}
public abstract class AbstractBase : IBase {
string ErrorMessage;
public abstract void AddData();
public abstract void DeleteData();
}
public class AClass : AbstractBase {
public override void AddData();
public override void DeleteData();
}
根据罗伯特·弗雷泽的评论更新
I know this may be basic but I cannot seem to add a member variable to an interface.
I tried inheriting the interface to an abstract class and add member variable to the abstract class but it still does not work. Here is my code:
public interface IBase {
void AddData();
void DeleteData();
}
public abstract class AbstractBase : IBase {
string ErrorMessage;
public abstract void AddData();
public abstract void DeleteData();
}
public class AClass : AbstractBase {
public override void AddData();
public override void DeleteData();
}
updated base on comment of Robert Fraser
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不能向接口添加字段。接口只能包含方法,因此只能在接口声明中声明方法、属性、事件。您可以使用属性来代替字段。
You cannot add fields to an interface.Interface can only contain methods , so only methods , properties , events can be declared inside an interface decleration.In place of field you can use a property.
为我工作。您缺少抽象类方法上的“public”和“void”。
Workd for me. You were missing the "public" and "void" on the abstract class methods.
由于接口仅声明非实现细节,因此您不能在接口中声明成员变量。
但是,您可以在接口上定义属性,并在类中实现该属性。
Since interfaces only declare non-implementation details, you cannot declare a member variable in an interface.
However, you can define a property on your interface, and implement the property in your class.
如果它是实现类需要实现的内容,则使用属性定义 ie
也就是说,如果它是需要私有的东西,那么它无论如何都不应该出现在界面中。
If it is something implementing classes need to implement then use a property definition i.e.
That said if it is something which needs to be private then that it not something which should be in an interface anyway.
您指的是属性而不是字段吗?
Did you mean a property instead of a field?