Unity如何加载泛型配置
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]拥有三个构造函数。
标签:
Microsoft Unity
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?