c# - CustomAttribute 名称可以简化

标签 c# visual-studio-2015

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

[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/

相关文章:

c# - 基于ANTLR v3的成熟编译器

c# - 部分类的 ReportDiagnostic

c# - 从 Visual Studio 文本选择(插入符号位置)获取 Roslyn SyntaxToken

css - Gulp 不会忽略带下划线的 SASS 偏音

c# - 使用 C# 从数据库中保存和检索 rtf 文本

c# - NoSuchElementException 尽管使用 WebDriverWait

c# - 在 C# 中使用具有 "recursive"关系的泛型

C# : how can i switch between my two network interface

visual-studio-2015 - Visual Studio 是否需要用于 ASP.NET 5 项目的 .sln 文件?它可以只使用 Global.json 吗?

git - 使用 Visual Studio Online 创建远程 GIT 分支