首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

结构设计有关问题,用什么方法能达到构造函数参数为this的目的

2013-09-06 
结构设计问题,用什么方法能达到构造函数参数为this的目的现在我遇到一个结构设计方面的问题,有人指点一下

结构设计问题,用什么方法能达到构造函数参数为this的目的
现在我遇到一个结构设计方面的问题,有人指点一下吗,谢谢!
不太会文字描述,我大概用下面这段代码来示意一下,这个能反映出我实际的需求,但是这段代码是有问题的。

有人会用正确的方法写了这个意思吗,谢谢!

(之所以这样设计,是因为 B 中希望访问到 A 中的一些方法,但是又不能 New A 或 Static A)

public class A
    {
        private B _b = new B(this); //问题出在了 this 这里。
        public B B
        {
            get
            {
                return _b;
            }
        }
    }
    public class B
    {
        private A _a;
        public B(A a)
        {
            _a = a;
        }
    }
设计 结构 结构设计
[解决办法]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public class A
    {
        private B _b;
        public A()
        { _b = new B(this); }
        public B B
        {
            get
            {


                return _b;
            }
        }
    }
    public class B
    {
        private A _a;
        public B(A a)
        {
            _a = a;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            Console.WriteLine(a.B);
        }
    }
}


[解决办法]
这不是结构设计的问题,给A写个构造函数就可以,

private B _b =null

public A(){
_b=new B(this);
}

热点排行