![](/img/trans.png)
[英]How to define parent/children relation with EntityFrameworkCore?
[英]How to define accessors for a children?
我有3节课:
public interface IParent
{
String World { get; }
}
public class Parent : IParent
{
public String World;
{
get
{
return "Hello " + this.World;
}
}
}
public class Children : Parent
{
public String World = "World";
}
我应该如何做才能使用Children
的World
属性调用Parent
的get访问器?
您可以使用第二个属性作为后缀,并将其设置为虚拟,以允许后代覆盖后缀
public class Parent : IParent
{
protected virtual string Suffix => "World";
public String World => "Hello " + Suffix;
}
public class Children : Parent
{
protected override string Suffix => "Again";
}
父母将显示“ Hello World”,孩子将显示“ Hello Again”。 这仅适用于运行时类型。 静态(即编译时间)类型无关紧要。
Parent p = new Children();
Console.WriteLine(p.World); // Displays "Hello Again"!
在这里, p
的静态类型是Parent
。 运行时类型为Children
。 这种行为称为多态性(C#编程指南) 。
真正的Parent
无法知道后缀“ Again”。
您可以使用将是虚拟的其他专用字段,因此可以在子级中覆盖它。
尝试这个:
public interface IParent
{
string HelloWorld { get; }
}
public class Parent : IParent
{
protected virtual string World { get; }
public string HelloWorld
{
get
{
return "Hello " + World;
}
}
}
public class Children : Parent
{
protected override string World { get; } = "World";
}
或者,您也可以通过构造函数传递字符串,然后可以在运行时设置值。
public interface IParent
{
string HelloWorld { get; }
}
public class Parent : IParent
{
private readonly string world;
public Parent(string world)
{
this.world = world;
}
public string HelloWorld
{
get
{
return "Hello " + world;
}
}
}
public class Children : Parent
{
public Children(string world) : base(world)
{
}
}
像这样使用它:
var children = new Children("World");
Console.WriteLine(children.HelloWorld);
这是回到前面。
如果需要的话 ,由继承类决定是否包含重写中的基类行为。 子类override
基本行为,但通过base
关键字具有对基本类的钩子。
因此:
public interface IParent
{
String World { get; }
}
public class Parent : IParent
{
public virtual String World
{
get
{
return "Hello";
}
}
}
public class Children : Parent
{
public override String World
{
get
{
return base.World + " World!";
}
}
}
该属性已经是父项的一部分。 但是,您需要一个受保护的set函数...在构造函数中进行设置,如下所示:
public interface IParent
{
String World { get; }
}
public class Parent : IParent
{
public String World { get; protected set; }
public Parent() { World = "Hello World"; }
}
public class Children : Parent
{
public Children() { World = "World"; }
}
但是,也许您正在寻找更像这样的东西:
public interface IParent
{
String World { get; }
}
public class Parent : IParent
{
public String World { get; private set; }
public Parent(String thing) { World = "Hello " + thing; }
}
public class Children : Parent
{
public Children() : base("World") { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.