简体   繁体   English

如何在继承类中强制实现抽象类成员?

[英]How to force implementation of an abstract classes members in the inheriting class?

I have the following two classes: 我有以下两节课:

abstract class LogItem    {       
    public String payload { get; set; }       
    public String serverId { get; set; }     
    public DateTime timeRecieved { get; set; }

}

  class MyLogItem : LogItem
{
  //No I want this to have to have the members from the abstract class above, as if it where an interface?
}

So in other words I am wanting a type if interface that can have definitions or variables which all classes that implement it have to have, but they could add more if they required ? 所以换句话说,我想要一个if接口类型,它可以具有实现它的所有类都必须具有的定义或变量,但是如果需要,它们可以添加更多的内容?

The above example builds, even if i dono add the members from the abstract class. 即使我不添加抽象类中的成员,上述示例也会生成。

edit Forget what I've said before. 编辑忘记我之前说过的话。 These are attributes, not methods. 这些是属性,而不是方法。 For them to be accessible on derived classes, you make them protected or public . 为了使它们在派生类上可访问,请将它们设置为protectedpublic The difference is that public members are visible to the world, while protected ones are visible to the class and subclasses. 区别在于,公共成员对全世界都是可见的,而受保护的成员对于阶级和子类是可见的。

Any class derived from your LogItem may have other variables. 从LogItem派生的任何类都可以具有其他变量。

abstract class LogItem    {       
    public String payload { get; set; }       
    public String serverId { get; set; }     
    public DateTime timeRecieved { get; set; }

}

 class MyLogItem : LogItem
{
  //No I want this to have to have the members from the abstract class above, as if it where an interface?
   private void TestMethod(){
     String test = payload;
   }
}

check out this post for more information 查看帖子以获取更多信息

Your MyLogItem class can reference any of the above members directly. 您的MyLogItem类可以直接引用任何上述成员。 They are accessible 它们是可访问的

You may declare an interface with those 您可以声明与这些接口

 public interface MyInterface {
     public String payload { get; set; }       
     public String serverId { get; set; }     
     public DateTime timeRecieved { get; set; }
 }

and your class 和你的班级

 public class MyLogItem : MyInterface 
{
   String _payload;
   public String payload { get{ return _payload; } set {_payload=value;} }
   ...
}

所述abstract关键字也可以应用于方法,如所描述这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM