[英]How can I directly access my base class property in the derived class without using methods or constructors?
class Animal
{
public bool isHungry { get; set; }
public int Age { get; set; }
public string Name { get; set; }
}
class Dog : Animal
{
Age = 5; //Gives error, "Age doesnt exist in current context"
public Dog()
{
Age = 5;//Works fine
Console.WriteLine("Dog");
}
}
I want to access the public properties directly, is it not possible?我想直接访问公共属性,不可以吗?
Code must be within methods - if you want to set a default value for all Dog
instances then the constructor is the proper place to do that.代码必须在方法中——如果你想为所有Dog
实例设置一个默认值,那么构造函数就是这样做的合适位置。
You could make the base property virtual and then override it in Dog
with a default value:您可以将基本属性设为虚拟,然后在Dog
中使用默认值覆盖它:
class Animal
{
public bool isHungry { get; set; }
public virtual int Age { get; set; }
public string Name { get; set; }
}
class Dog : Animal
{
public override int Age {get; set;} = 5;
public Dog()
{
Console.WriteLine("Dog");
}
}
but that seems like overkill in this simple example.但在这个简单的例子中,这似乎有点矫枉过正。
D Stanley is totally right. D 斯坦利是完全正确的。 Another way to do it is to use new
keyword.另一种方法是使用new
关键字。 This is a little bit cleaner in my opinion but totally depends on the context and problem.在我看来,这有点干净,但完全取决于上下文和问题。
class Dog : Animal
{
public new int Age = 5;
}
Presumably, not all animals would have the same age ( 5 in this case ).据推测,并非所有动物的年龄都相同(在这种情况下为 5岁)。 Set your properties via the constructor, or if they have public setters, instantiate an instance of Dog
and then set its Age
property.通过构造函数设置属性,或者如果它们有公共设置器,则实例化Dog
的实例,然后设置其Age
属性。
public abstract class Animal
{
protected Animal()
{
}
public int Age { get; set; }
}
public class Dog : Animal
{
public Dog(int age)
{
this.Age = age;
}
public override string ToString()
{
return $"{nameof(Dog)}: {nameof(Age)} - {this.Age}";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.