在Unity App.Config文件中包含泛型类

时间:2009-01-18 06:01:42

标签: c# generics app-config unity-container

我有一个类ISimpleCache<IBrokeredDataObject>的类,我想在App.Config文件中添加为类型别名(然后是类型)

<typeAlias alias="ISimpleCacheOfIBrokeredDataObject" type="MyApplication.ISimpleCache<IBrokeredDataObject>, MyApplication" />
由于&lt;&gt;,

显然是错误的,但我不相信逃避它们;

<typeAlias alias="ISimpleCacheOfIBrokeredDataObject" type="MyApplication.ISimpleCache&lt;IBrokeredDataObject&gt;, MyApplication" />

也是正确的。

我目前正在将我的代码拆分为使用Unity,因此距离可编译的代码库太远而无法快速测试,并希望在此处获得一些确认。

4 个答案:

答案 0 :(得分:22)

查看this博文:

  

为了编写泛型类型,请使用`符号,后跟接口/类接收的泛型类型的数量。

同一页的评论说:

  

为了在泛型中使用常量类型,您需要使用括号([[ ]])。

所以我猜你的配置文件应该包含这样的内容:

<typeAlias alias="ISimpleCacheOfIBrokeredDataObject"
   type="MyApplication.ISimpleCache`1[[MyApplication.IBrokeredDataObject, MyApplication]], MyApplication" />

请注意使用“严重重音”或“反引号”字符(`),而不是正常的单引号(')。

答案 1 :(得分:14)

我会对上面的答案发表评论,但我的得分还不够高。

此处记录Type.GetType方法(字符串)的语法:http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx

有很多例子,其中一些我粘贴在下面。

具有一个类型参数的泛型类型

Type.GetType("MyGenericType`1[MyType]")

具有两个类型参数的泛型类型

Type.GetType("MyGenericType`2[MyType,AnotherType]")

具有两个程序集限定类型参数的泛型类型

Type.GetType("MyGenericType`2[[MyType,MyAssembly],[AnotherType,AnotherAssembly]]")

具有程序集限定类型参数的程序集限定泛型类型

Type.GetType("MyGenericType`1[[MyType,MyAssembly]],MyGenericTypeAssembly")

泛型类型,其类型参数是具有两个类型参数的泛型类型

Type.GetType("MyGenericType`1[AnotherGenericType`2[MyType,AnotherType]]")

答案 2 :(得分:2)

这就是你使用接收两种泛型类型的类型的方法:

<section name="doubleFamilyConfig"
         type="ConfigTest.Configuration.FamilySection`2[
               [ConfigTest.Types.Child, ConfigTest],
               [ConfigTest.Types.Parent, ConfigTest]
               ],
               ConfigTest" />

如果您愿意,可以在不同的行上使用每种类型,以便更容易理解。请注意,第一个括号必须在类型后面(FamilySection`2 ** [**]。

答案 3 :(得分:1)

这是强签名类型作为通用参数。

<typeAlias alias="IPublisherOfXElement" type="MyLib.IX.IPublisher`1[[System.Xml.Linq.XElement, System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], MyLib.IX" />