【问题标题】:Models With Multiple Inheritance in C# [duplicate]C# 中具有多重继承的模型 [重复]
【发布时间】:2016-03-11 10:14:43
【问题描述】:

在我的网站中,我为每个页面使用了一个视图模型。每个视图模型仅包含属性,没有其他内容。几个页面使用同一组属性。我想做的是为每组属性创建一个类,然后在每个页面视图模型上使用相关组。

示例属性组:

public class GroupCar
{
    public string CarName { get; set; }
    public string CarColour { get; set; }
    public string CarLink { get; set; }
}

public class GroupSport
{
    public string SportName { get; set; }
    public string SportLocation { get; set; }
    public string SportLink { get; set; }
}

public class GroupFood
{
    public string FoodName { get; set; }
    public string FoodPrice { get; set; }
    public string FoodLink { get; set; }
}

现在,在我的视图模型中,我将拥有该页面的多个属性,并且我还想使用这些组中的一些属性。

我可以轻松继承其中一个组

public class VMMyPage : GroupCar
{
    //My Bespoke Properties
}

我如何继承多个组...类似于:

public class VMMyPage : GroupCar, GroupSport, GroupFood
{
    //My Bespoke Properties
}

我知道您不能在 C# 中执行此操作,但有解决方法吗?我已经阅读了几篇关于使用接口类的文章,但是没有我想要实现的确切示例?

【问题讨论】:

    标签: c# inheritance model multiple-inheritance


    【解决方案1】:

    C# 中,classes 仅允许来自单亲classinherit。但您可以使用interfacesclassinterface(s) 的组合。

    所以,在这里你可以将属性存储在Interfaces 中,然后你就可以完成你的逻辑了。

    了解更多关于继承的信息read

    【讨论】:

    • 从 OP 的问题来看,我认为他并不真正关心是否有合同,无论这些属性是否可用,我认为他只是想访问它们而无需键入/复制他们重新来过。
    • 是的,我不想在每个视图模型中都写出它们。我想要一个中心位置,我可以在其中轻松地同时管理所有模型。
    【解决方案2】:

    这就是您使用接口实现它的方式。但是通过从接口继承,您必须在视图模型类中实现属性。

        public interface IGroupCar
        {
            string CarName { get; set; }
            string CarColour { get; set; }
            string CarLink { get; set; }
        }
    
        public interface IGroupSport
        {
            string SportName { get; set; }
            string SportLocation { get; set; }
            string SportLink { get; set; }
        }
    
        public interface IGroupFood
        {
            string FoodName { get; set; }
            string FoodPrice { get; set; }
            string FoodLink { get; set; }
        }
    
        public class VMMyPage : IGroupCar, IGroupSport, IGroupFood
        {
            public string CarName { get; set; }
            public string CarColour { get; set; }
            public string CarLink { get; set; }
            public string SportName { get; set; }
            public string SportLocation { get; set; }
            public string SportLink { get; set; }
            public string FoodName { get; set; }
            public string FoodPrice { get; set; }
            public string FoodLink { get; set; }
            // Your custom view model properties          
        }
    

    【讨论】:

    • 好的,如果你使用接口,你仍然需要在模型中再次写出所有属性?
    • 是的,接口只是一个签名类,你必须继承它的所有属性。
    • 好的,谢谢您的回答。不确定接口在这种情况下是否真的对我有帮助。我的想法是我只需将变量写出一次,然后我就可以从一个中心位置添加、删除、更新和使用它们。
    • @HenkHolterman 是对的,你必须通过类继承来做到这一点。
    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    • 2011-08-22
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多