Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 具有继承嵌套类的MVC模型_C#_Asp.net Mvc_Inheritance_Model View Controller_Interface - Fatal编程技术网

C# 具有继承嵌套类的MVC模型

C# 具有继承嵌套类的MVC模型,c#,asp.net-mvc,inheritance,model-view-controller,interface,C#,Asp.net Mvc,Inheritance,Model View Controller,Interface,希望实现一个有点像这样的MVC模型,但是person类有一个Telecoms类,可以是phoneline或PhonelineAndBroadband类,我可以在其中轻松访问ITelecom Price()方法以获得一个列表。这是最好的方法吗?在Person类中会出现什么 class Person { } abstract class Telecoms { } interface ITelecoms { void Price(); } class Phoneline : Tele

希望实现一个有点像这样的MVC模型,但是person类有一个Telecoms类,可以是phoneline或PhonelineAndBroadband类,我可以在其中轻松访问ITelecom Price()方法以获得一个列表。这是最好的方法吗?在Person类中会出现什么

class Person
{

}

abstract class Telecoms
{

}

interface ITelecoms
{
    void Price();
}

class Phoneline : Telecoms, ITelecoms
{
    public void Price() {...}    
}

class PhonelineAndBroadband : Telecoms, ITelecoms
{
    public void Price() {...}    
}

Person类的属性类型应为
ITelecoms

public class Persons
{
    public ITelecoms Telecom {get;set;}
}

Person p1 = new Person {Telecom = new Phoneline()};
Person p2 = new Person {Telecom = new PhonelineAndBroadband()};

List<Person> persons = new List<Person>{p1, p2};

persons.ForEach(r=> r.Telecom.Price());
公共阶层人士
{
公共ITelecoms电信{get;set;}
}
人员p1=新人员{Telecom=新电话线()};
人员p2=新人员{Telecom=新电话线和宽带();
名单人员=新名单{p1,p2};
persons.ForEach(r=>r.Telecom.Price());

我建议只使用抽象类。这将是你的基础课。它将包含一个抽象方法,该方法包含Price()方法。然后,您可以去掉多态性,这是面向对象编程的基本原理之一,以便将此方法实现到子类中。 因此,消除接口,因为Price()将在基本抽象类中访问,而不是通过添加ITelecoms接口来增加设计的复杂性

abstract class Telecoms
{
    public abstract void Price();
}
然后是你的子类

class Phoneline : Telecoms
{
    public override void Price() {...}    
}

class PhonelineAndBroadband : Telecoms
{
    public override void Price() {...}    
}
有了这样的代码,您将拥有一个干净、紧凑、尊重OO的设计