现在的位置: 首页 > 综合 > 正文

关于ObjectBuilder里DefaultCreaionPolicy的一点说明

2012年05月03日 ⁄ 综合 ⁄ 共 2186字 ⁄ 字号 评论关闭

最近在学习MS的一套Dependency Inject的Framework库ObjectBuilder。 

在看到DefaultCreationPolicy里注意到这个类的说明是这样的:

/// <summary>
 /// Simple default creation policy which selects the first public constructor
 /// of an object, using the builder to resolve/create any parameters the
 /// constructor requires.
 /// </summary>

所以对些进行了一个小试验:

写了一个Build的Function:

            private void Build()       

{
            BuilderStrategyChain ochain = new BuilderStrategyChain();

            PolicyList oPolicylist = new PolicyList();
            ochain.Add(new SingletonStrategy());
            ochain.Add(new CreationStrategy());
            oPolicylist.Set<ISingletonPolicy>(new SingletonPolicy(true), typeof(Class1), null);
            ConstructorPolicy oconstructorpolicy = new ConstructorPolicy();
            oconstructorpolicy.AddParameter(new ValueParameter<string>("Susan"));
           
            oPolicylist.SetDefault<ICreationPolicy>(oconstructorpolicy);
            //oPolicylist.SetDefault<ICreationPolicy>(new DefaultCreationPolicy());

            Locator olocator =new Locator();
            olocator.Add(typeof(ILifetimeContainer), new LifetimeContainer());
            BuilderContext ocontext = new BuilderContext(ochain, olocator, oPolicylist);
            Class1 obj1 = (Class1)ochain.Head.BuildUp(ocontext, typeof(Class1),null, null);
            Class1 obj2 = (Class1)ochain.Head.BuildUp(ocontext, typeof(Class1), null, null);
            if (obj1 != obj2)
                MessageBox.Show("not equal");
            else if (obj1==obj2)
            {
                MessageBox.Show("equal");
            }

        }

这里的用到一个Class1类。

我试了两个版本:

版本一:

using System;
using System.Collections.Generic;
using System.Text;

    class Class1
    {
        string name = "Andy";

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
       
        public Class1()
        {

        }
        public Class1(string name)
        {
            this.Name = name;
        }
    }

版本二:

   class Class1
    {
        string name = "Andy";

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        public Class1(string name)
        {
            this.Name = name;
        }
        public Class1()
        {

        }
       
    }

 

先后运行一下测试程序,结果第一可以正确显示,第二个则会出现运行时错误。

有兴趣的朋友可以自己动手试一下。

总结:

所以在一类有多个Public类型的构造函数时,最好是把无参的构造函数放在代码的最前面。

【上篇】
【下篇】

抱歉!评论已关闭.