[MyAttribute(Name = value)]中的“Name = value”是什么

时间:2017-02-17 11:58:39

标签: c# attributes custom-attributes

我不知道使用什么词语进行谷歌搜索。

考虑这个属性:

 [MyAttribute(MyOption=true,OtherOption=false)]

Name=value部分是什么?我如何在自己的自定义属性中实现它?

4 个答案:

答案 0 :(得分:5)

您可以通过声明公共实例(非静态)属性或字段来使用它:

[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    public string TestValue { get; set; }
}

[My(TestValue = "Hello World!")]
public class MyClass{}

因此它的工作方式与对象初始化程序语法类似,但使用()代替{}

如果为构造函数提供属性参数,则必须先传递参数:

[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
    public string TestValue { get; set; }

    public MyAttribute(int arg)
    {}
}

[My(42, TestValue = "Hello World!")]
public class MyClass{}

有关详细信息,请参阅this tutorial

答案 1 :(得分:3)

C#规范17.2 Attribute specification

  

属性由属性名称和可选列表组成   位置命名参数。位置参数(如果有的话)   在命名参数之前。位置论证由a组成   属性参数表达式;命名参数由名称组成,   然后是等号,然后是   attribute-argument-expression,它们一起受到约束   与简单分配相同的规则。命名参数的顺序不是   显著。

所以这里

[MyAttribute(MyOption=true,OtherOption=false)]

您有两个命名参数。什么是命名论点?同样,C#规范17.3.1 Compilation of an attribute

  

名称必须标识非静态读写公共字段或属性   T(属性类型)。如果T没有这样的字段或属性,那么编译时错误   发生。

非常清楚,我相信。这些名称是带有getter和setter的非静态公共属性(很可能)或MyAttribute类中声明的非静态公共字段:

 public class MyAttribute : Attribute
 {
     public bool MyOption { get; set; }
     public bool OtherOption { get; set; }
 }

如果您需要更多命名参数 - 添加另一个非静态公共读写属性或带有您要使用的名称的非静态公共字段。

 public class MyAttribute : Attribute
 {
     public bool MyOption { get; set; }
     public bool OtherOption { get; set; }
     public int Answer { get; set; }
     // public int Answer;  <- another option
 }

用法(顺序无关紧要):

 [MyAttribute(MyOption=true, Answer=42, OtherOption=false)]

答案 2 :(得分:2)

在创建属性实例时指定属性。

属性可以有构造函数参数和属性 - 这个是设置属性。请注意,您可以混合使用位置构造函数参数,命名构造函数参数和属性,如下面的示例所示:

using System;
using System.Linq;
using System.Reflection;

[AttributeUsage(AttributeTargets.All)]
public class DemoAttribute : Attribute
{
    public string Property { get; set; }
    public string Ctor1 { get; set; }
    public string Ctor2 { get; set; }
    public string Ctor3 { get; set; }

    public DemoAttribute(string ctor1,
                         string ctor2 = "default2", 
                         string ctor3 = "default3")
    {
        Ctor1 = ctor1;
        Ctor2 = ctor2;
        Ctor3 = ctor3;
    }
}

[Demo("x", ctor3: "y", Property = "z")]
public class Test
{
    static void Main()
    {
        var attr = (DemoAttribute) typeof(Test).GetCustomAttributes(typeof(DemoAttribute)).First();
        Console.WriteLine($"Property: {attr.Property}");
        Console.WriteLine($"Ctor1: {attr.Ctor1}");
        Console.WriteLine($"Ctor2: {attr.Ctor2}");
        Console.WriteLine($"Ctor3: {attr.Ctor3}");
    }
}

请注意命名构造函数参数的:与属性赋值的=之间的差异。

此代码的输出是

Property: z
Ctor1: x
Ctor2: default2
Ctor3: y

不幸的是,C#规范调用了命名的构造函数参数和属性&#34;命名参数&#34;在这种情况下:(

答案 3 :(得分:1)

这称为属性的命名参数。实际上是属性类的属性。有关详情,请访问https://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx

相关问题