关于ObjectBuilder里DefaultCreaionPolicy的一点说明

本文通过一个具体的测试案例探讨了MS的Dependency Inject Framework ObjectBuilder中DefaultCreationPolicy的行为。实验对比了不同构造函数顺序对实例化结果的影响,并总结了最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习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类型的构造函数时,最好是把无参的构造函数放在代码的最前面。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值