简体   繁体   English

如何强制派生类在 C# 中实现属性

[英]How to force derived class to implement a property in C#

I have scenario like below我有如下场景

public abstract class Test 
{
   public string name; 
   public abstract bool is_selected();
}

public class Campus : Test 
{  

}

Now Campus must and should implement is_selected() method otherwise it throws an error.现在 Campus 必须并且应该实现 is_selected() 方法,否则它会抛出错误。 Adding to the same lines I want 'name' field also like that.添加到相同的行中,我也希望“名称”字段也如此。 I mean name field must be given a value.我的意思是必须给 name 字段一个值。

How can I do that?我怎样才能做到这一点? Any help greatly appreciated.非常感谢任何帮助。

Thanks in advance :)提前致谢 :)

I can find two options我可以找到两个选项

  1. Use a parameterized constructor, so the derived class must provide a constructor which initialize the fields.使用参数化构造函数,因此派生类必须提供一个构造函数来初始化字段。
public abstract class Test 
{
   public string name;
   protected Test(string name){ this.name = name; }
}

public class Campus : Test 
{
   public Campus() : base("Init the name here") {}
}
  1. Use an abstract property, this is already metioned by other people.使用抽象属性,其他人已经提到过。
public abstract class Test 
{
   public abstract string name { get; }
}

public class Campus : Test 
{  
   public override string name => "name";
}

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

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