2012-01-16 1 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 ...)は例外をスローします。 –

+0

.Netのどのバージョンを使用していますか(つまり、プロジェクトの.Netフレームワークのターゲット) –

+0

ターゲットフレームワークは4です(クライアントプロファイルではありません)。 –

関連する問題