如何在C类中访问A类的公共属性MyProperty

时间:2016-06-21 13:46:48

标签: c#

我有以下代码:

public class A
{
   public int MyProperty {get; set;}
}

public class B
{
   A myInstance = new A();
   myInstance.MyProperty = 10;
}

public class C
{
   public void InvokeA()
   {
        //How to access MyPropery here?
        BInstance = new B();
        Console.WriteLine(B.myInstance.MyProperty.ToString()); 
   }
}

我正在寻找一种如上所述访问MyProperty的方法。继承不是一个选项,因为我的类C已经从某个基类继承。没有将任何给定类声明为静态的方法会很好!

谢谢, ORZ

3 个答案:

答案 0 :(得分:1)

为了实现您的目标,您需要将B.MyInstance公开为B类的属性,就像您将A.MyProperty公开为A的属性一样类。

修改:根据其他人对static关键字使用的评论,您可能希望您的代码看起来像这样:

public class A
{
   public int MyProperty { get; set; }
}

public static class B
{
   static B()
   {
       MyInstance = new A();
       MyInstance.MyProperty = 10;
   }

   public static A MyInstance { get; set; }
}

public class C
{
   // not sure what your intention is here
   public C()
   {
       System.Console.WriteLine(B.MyInstance.MyProperty.ToString()); // "10\n"
   }
}

答案 1 :(得分:1)

考虑以下课程:

public class A
{
    public int MyProperty { get; set; }
}

public class B
{
    public A GetAInstance()
    {
        A myInstance = new A();
        myInstance.MyProperty = 10;

        return myInstance;
    }
}

public class C
{
    private B BInstance;

    public void InvokeA()
    {
        BInstance = new B();

        Console.WriteLine(BInstance.GetAInstance());
    }
}

然后你将在Main中创建你的C实例:

    static void Main(string[] args)
    {
        C cInstance = new C();
        cInstance.InvokeA();
    }

答案 2 :(得分:0)

是。您可以从A到B继承类,如下所示:

public class A
{
   public int MyProperty {get; set;}
}

public class B : A
{
    public B()
        : A() 
    {
        MyProperty = 1;
    }
}

现在你可以做到:

(new B()).MyProperty

或使用Singleton方法解决:

public class B
{
    private static _a;

    public class A
    {
        public int MyProperty {get; set;}
    }

    public static A AA {
        if (_a == null) {
            _a = new A();
        }

        return _a;
    }  
}

此实施将返回

B.A.MyProperty.ToString();
相关问题