gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:01:39 26 4
gpt4 key购买 nike

有没有办法用泛型类型的 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);

最佳答案

我怀疑问题出在您定义类声明的方式上。这是一个代码片段,它在上下文中用 [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);

关于c# - 如何使用 ReSharper SDK 创建 [CustomAttribute(typeof(GenericType<,>))]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8877628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com