如何使用ReSharper SDK创建[CustomAttribute(typeof(GenericType<,>))]?

时间:2012-01-16 09:00:52

标签: c# .net resharper resharper-6.1 resharper-sdk

有没有办法用typeof表达式创建一个带有泛型类型的属性?

以下代码仅部分有效:

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 个答案:

答案 0 :(得分: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);