简体   繁体   English

自定义属性名称可以简化

[英]CustomAttribute Name Can Be Simplified

I have a class with a custom attribute defined like this:我有一个自定义属性的类,定义如下:

[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 highlights the line Visual Studio 突出显示该行

[MyAttribute("ClassName")]

with this message:这条消息:

IDE0001 : Name Can Be Simplified. IDE0001:名称可以简化。

It suggests to shorten the attribute definition to My("ClassName") which doesn't work because the attribute is not defined as "My".它建议将属性定义缩短为 My("ClassName") 这不起作用,因为该属性未定义为“My”。

This suggestion seems to be based on the way the default attributes are implemented where either MyAttribute or My could be used.这个建议似乎基于默认属性的实现方式,其中可以使用 MyAttribute 或 My。 How would I implement my custom attribute to accept either My or MyAttribute like the default attributes do?我将如何实现我的自定义属性以像默认属性一样接受 My 或 MyAttribute?

Typically when you derive from attribute you do not use the suffix Attribute when using it: 通常,当您从属性派生时,在使用后缀时不使用后缀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". 建议将属性定义缩短为My(“ ClassName”),因为该属性未定义为“ My”,因此无法使用。

(It's compiler magic, and it works) (这是编译器的魔力,并且有效)

How would I implement my custom attribute to accept either My or MyAttribute like the default attributes do? 我如何实现自定义属性以接受My或MyAttribute像默认属性一样?

You already did, you can use [MyAttribute("whatever")] and it will compile just fine. 您已经做过,可以使用[MyAttribute("whatever")] ,它将可以正常编译。

If you want to use MyAttribute , but not just My , then you need to call you attribute class MyAttributeAttribute . 如果要使用MyAttribute而不是My ,则需要调用属性类MyAttributeAttribute See eg 见例如

public class XmlAttributeAttribute : Attribute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM