c#中多个属性对单个属性的继承

本文关键字:属性 单个 继承 | 更新日期: 2023-09-27 18:08:56

如何从一个类中继承多个属性呢?示例

这里是实际代码(So Far)

class NetWorkInterface
{
    public double Vlan;
    public string Ip;
}
class Port : NetWorkInterface
{
    public double PortNumber;
}
public void test ()
{
    Port newport = new Port();
    newport.PortNumber = 7;
    newport.Vlan = 100
}

我想能够添加多个接口到一个端口

c#中多个属性对单个属性的继承

我认为你不应该在这里使用继承。

如果您希望Port包含NetworkInterfaces的集合,那么Port的更好定义可能是:

class Port
{
    public double PortNumber;
    public NetworkInterface[] networkInterfaces;
}

    public class Port
    {
        public double PortNumber { get; set; }
        public IEnumerable<NetworkInterface> NetworkInterfaceList { get; set; }
    }

每个类可以继承一个类(c#中没有多重继承),或者实现多个接口,或者两者都做

public interface NetWorkInterface1
{
  double Vlan {get; set;} 
}
public interface NetWorkInterface2
{
   string Ip {get; set;}
}
class Port : A /* (inherit class before interface) port inherits A & A inherits B*/, NetWorkInterface1, NetWorkInterface2 /* implements interface 1 & 2*/
{
    public double PortNumber;
    public double Vlan {get; set;} 
    public string Ip {get; set;}
}
public class A : B /* A inherits B */
{
  public string AStuff; 
}   
public  class B
{
  public string BStuff;         
}

public void test ()
{
    Port newport = new Port();
    newport.PortNumber = 7;
    newport.Vlan = 100;
    newport.AStuff = "A"; 
    newport.BStuff = "B"; 
}