C# C语言中的多重继承模型#

C# C语言中的多重继承模型#,c#,inheritance,model,multiple-inheritance,C#,Inheritance,Model,Multiple Inheritance,在我的站点中,我为每个页面使用一个视图模型。每个视图模型仅由属性组成,不包含其他内容。几个页面使用相同的属性组。我想做的是为每组属性创建一个类,然后在每个页面视图模型上使用相关组 示例属性组: public class GroupCar { public string CarName { get; set; } public string CarColour { get; set; } public string CarLink { get; set; } } publ

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

示例属性组:

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#
中没有确切的例子说明我想要实现什么,
仅允许
从单个父类继承
。但您可以使用
接口
或一个
接口的组合

因此,您可以在这里将属性存储在
接口中
,并完成您的逻辑


要了解有关继承的更多信息,请使用接口实现继承。但是通过从接口继承,您必须实现viewmodel类中的属性

    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          
    }

从OP的问题来看,我不认为他真的在乎是否有合同,不管这些属性是否可用,但我认为他只想访问它们,而不必再次键入/复制它们。是的,我不想在每个视图模型中都写出来。我想要一个中心位置,在这里我可以同时轻松地跨所有模型管理它们。好吧,如果你使用接口,你仍然需要在模型中再次写出所有属性?是的,你需要,接口只是一个签名类,你必须继承它的所有属性。好的,谢谢你的回答。在这种情况下,我不确定接口是否真的能帮助我。我的想法是,我只需要写出一次变量,然后我就可以从一个中心位置添加、删除、更新和使用它们。@HenkHolterman是对的,你必须用类继承来完成这项工作。