Spring.Net -- 如何使用用户自定义类型转换器 (Custom Type Converter )

有时我们需要在Spring.net创建对象时,自动将spring.xml配置中string类型转换为指定类型。

例如:

我们有如下两个个自定义类,其中ExoticType类在DependsOnExoticType类中被作为属性使用

public class ExoticType
{
    private string name;
       
    public ExoticType(string name)

{ this.name = name;
    }

    public string Name
    {
        get { return this.name; }
    }
}

 

 

public class DependsOnExoticType
{
    public DependsOnExoticType() {}
   
    private ExoticType exoticType;
       
    public ExoticType ExoticType
    {
        get { return this.exoticType; }
        set { this.exoticType = value; }
    }
   
    public override string ToString()
    {
        return exoticType.Name;
    }
}

 

在Spring.net配置中初始化时希望用string值赋给ExoticType类型属性,这时需要一个TypeConverter在后台进行类型转换。

<object name="sample" type="SimpleApp.DependsOnExoticType, SimpleApp">
  <property name="exoticType" value="aNameForExoticType"/>
</object>

 

我们需要自定义个TypeConverter如下:

public class ExoticTypeConverter : TypeConverter
{
public ExoticTypeConverter()
{
}

public override bool CanConvertFrom (
ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof (string))
{
return true;
}
return base.CanConvertFrom (context, sourceType);
}

public override object ConvertFrom (
ITypeDescriptorContext context,
CultureInfo culture, object value)
{
string s = value as string;
if (s != null)
{         
return new ExoticType(s.ToUpper());
}
return base.ConvertFrom (context, culture, value);
}
}

 

最后,我们需要在spring.xml配置中使用CustomeConverterConfigurer注册自定义的TypeConverter<object id="customConverterConfigurer"
type="Spring.Objects.Factory.Config.CustomConverterConfigurer, Spring.Core">
  <property name="CustomConverters">
    <dictionary>
      <entry key="SimpleApp.ExoticType">
        <object type="SimpleApp.ExoticTypeConverter"/>
      </entry>
    </dictionary>
  </property>
</object>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值