Unity如何加载泛型配置

本文介绍如何使用Unity的AutomaticTypeLookup进行类型配置,包括定义assembly和namespace、设置类型别名及泛型配置方法。

Unity提供Automatic Type Lookup,你可以在配置节中定义assembly和namespace,比如mscorlib和System:

<unity xmlns=”http://schemas.microsoft.com/practices/2010/unity”>
  <namespace name=”System” />
  <assembly name=”mscorlib, 2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ />

  <container />
</unity>

你可以为类型定义别名,默认Unity为基元类型定义了对应的别名,等同于C#中的关键字。比如System.Int32对应int(下面的int别名可以省略):

<unity xmlns=”http://schemas.microsoft.com/practices/2010/unity”>
  <namespace name=”System” />
  <assembly name=”mscorlib, 2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ />

  <alias alias=”int” type=”System.Int32″ />

  <container />
</unity>

泛型是一种特殊类型,它不同于一般的类型定义。比如对于Dictionary<String, Int32>它的类型输出是:System.Collections.Generic.Dictionary`2[System.String,System.Int32]。在Unity中可以通过以下语法配置:

IList<T> => IList[T]
IDictionary<K, V> => IDictionary[K, V]

假设现在要注册一个IDictionary<String, Int32>的实现:

<unity xmlns=”http://schemas.microsoft.com/practices/2010/unity”>
  <namespace name=”System” />
  <namespace name=”System.Collections.Generic” />
  <assembly name=”mscorlib, 2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ />

  <container>
    <register type=”IDictionary[string, int]” mapTo=”Dictionary[string, int]“>
      <constructor />
    </register>
  </container>
</unity>

如果没有自定义别名,可以在对应的类型中以[]方式添加完成的类型信息:

<unity xmlns=”http://schemas.microsoft.com/practices/2010/unity”>
  <namespace name=”System” />
  <namespace name=”System.Collections.Generic” />
  <assembly name=”mscorlib, 2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089″ />

  <container>
    <register type=”IDictionary[string, [System.Int32]]” mapTo=”Dictionary[string, [System.Int32]]”>
      <constructor />
    </register>
  </container>
</unity>

需要注意的是一个类型有多个构造函数时,需要显示指定一个构造函数。比如Dictionary[K, V]拥有三个构造函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值