访问对象中对象的属性

Qua*_*nel 2 c# multiple-inheritance

我有3个类MetaA,MetaB和MetaC.每个都有许多属性.

在某些情况下,只有一个类包含所有三个Meta类的属性(例如,MetaComposite)会很好.在复合类中,我尝试了每个MetaA,B和C的创建和实例,希望我可以像这样访问属性:

Meta Composite mc = new MetaComposite();
mc.MetaA.Property1 = "Hello";
Run Code Online (Sandbox Code Playgroud)

由于C#不允许多重继承,因此创建一个由其他类组合的类的最佳方法是什么?我可以在复合类中放置字段并编写getter和setter来传递属性值,但这将是很多重复的代码.

这里的正确方法是什么?

Mau*_*kom 5

如何为所有三个Meta类创建接口,并让MetaComposite类实现所有这三个接口.MetaComposite类可以实例化正确的Meta类并调用它来执行所需的属性.

这是一个例子:

public interface IMeta1
{
   int Metaproperty1 {get; set;}
}

public interface IMeta2
{
   int Metaproperty2 {get; set;}
}

public interface IMeta3
{
   int Metaproperty3 {get; set;}
}

public class MetaComposite : IMeta1, IMeta2, IMeta3
{
    private readonly Meta1 _meta1;
    private readonly Meta2 _meta2;
    private readonly Meta3 _meta3;

    public MetaComposite()
    {
        _meta1 = new Meta1();
        _meta2 = new Meta2();
        _meta3 = new Meta3();
    }

    public int Property1 
    {
        get { return _meta1.Property1; }
        set { _meta1.Property1 = value; }
    }

    public int Property2 
    {
        get { return _meta2.Property2; }
        set { _meta2.Property2 = value; }
    }

    public int Property3
    {
        get { return _meta3.Property3; }
        set { _meta3.Property3 = value; }
    }
}
Run Code Online (Sandbox Code Playgroud)