2012-01-16 26 views
3

有沒有辦法使用泛型類型創建typeof表達式的屬性?如何使用ReSharper SDK創建[CustomAttribute(typeof(GenericType <,>))]?

下面的代碼工作只是部分:

CSharpElementFactory factory = ... 
IClassDeclaration typeDeclaration = ... 

IClassDeclaration classDeclaration = ... 
IType[] attributeTypeParameters = 
    (from typeParameter in classDeclaration.TypeParameters 
    select (IType)TypeFactory.CreateUnknownType(module)).ToArray(); 
IType classType = TypeFactory.CreateType(classDeclaration.DeclaredElement, 
             attributeTypeParameters); 

var attribute = factory.CreateAttribute(
    new SpecialAttributeInstance(
     ClrTypeNames.ContractClassAttribute, 
     module, 
     () => new[] { new AttributeValue(classType) }, 
     Enumerable.Empty<Pair<string, AttributeValue>>)); 
typeDeclaration.AddAttributeAfter(attribute, null); 

回答

1

我懷疑問題是要定義你的類聲明的方式。下面是其中裝飾上下文中的類[ContractClass(typeof(Dictionary<,>))]

ClrTypeName contractClassAttribute = 
    new ClrTypeName("System.Diagnostics.Contracts.ContractClassAttribute"); 
ClrTypeName someGenericClass = new ClrTypeName("System.Collections.Generic.Dictionary`2"); 

var module = provider.PsiModule; 
var owner = provider.GetSelectedElement<IClassDeclaration>(true, true); 
var factory = CSharpElementFactory.GetInstance(module); 

var someGenericTypeElement = TypeElementUtil.GetTypeElementByClrName(someGenericClass, module); 
var unknownType = TypeFactory.CreateUnknownType(module); 
var someGenericType = TypeFactory.CreateType(someGenericTypeElement, unknownType, unknownType); 
var contractClassTypeElement = TypeElementUtil.GetTypeElementByClrName(contractClassAttribute, module); 
var attribute = factory.CreateAttribute(contractClassTypeElement, new[] {new AttributeValue(someGenericType)}, 
             EmptyArray<Pair<string, AttributeValue>>.Instance); 
owner.AddAttributeAfter(attribute, null); 
+0

'TypeElementUtil.GetTypeElementByClrName(someGenericClass,模塊)的代碼片段'爲空。所以'TypeFactory.CreateType(someGenericTypeElement ...'引發一個異常 – 2012-01-17 06:28:06

+0

你使用的是什麼版本的.Net(我的意思是,該項目的.Net框架目標。) – 2012-01-17 12:58:42

+0

目標框架是4(不是客戶端配置文件)。 – 2012-01-17 21:50:52

相關問題