gpt4 book ai didi

c# - CustomAttribute 名称可以简化

转载 作者:行者123 更新时间:2023-11-30 20:21:33 31 4
gpt4 key购买 nike

我有一个自定义属性定义如下的类:

[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
private string name;

public MyAttribute(string name)
{
this.name = name;
}
}
public class MyClass
{
[MyAttribute("ClassName")]
public string ClassName { get; set; }

}

Visual Studio 突出显示该行

[MyAttribute("ClassName")]

带有此消息:

IDE0001 : Name Can Be Simplified.

它建议将属性定义缩短为 My("ClassName") 这不起作用,因为该属性未定义为“My”。

这个建议似乎是基于默认属性的实现方式,其中可以使用 MyAttribute 或 My。我将如何实现我的自定义属性以像默认属性那样接受 My 或 MyAttribute?

最佳答案

通常,当您从属性派生时,您不使用后缀 Attribute使用时:

public class MyClass
{
[My("ClassName")]
public string ClassName { get; set; }
}

It suggests to shorten the attribute definition to My("ClassName") which doesn't work because the attribute is not defined as "My".

(这是编译器的魔法,而且有效)

How would I implement my custom attribute to accept either My or MyAttribute like the default attributes do?

你已经这样做了,你可以使用 [MyAttribute("whatever")] 它会编译得很好。

关于c# - CustomAttribute 名称可以简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33744095/

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