簡體   English   中英

自定義屬性的構造函數如何獲取可選參數

[英]how the constructor of custom attribute take optional parameters

嗨,大家好我在互聯網上瀏覽自定義屬性。 我掌握了這個概念但是,驚訝和混淆,看到他們通過屬性類的構造函數設置屬性值作為參數,該參數不從構造函數中獲取任何參數作為值。 請澄清核心概念。

[DeBugInfo(45, "Zara Ali", "12/8/2012", **Message = "Return type mismatch"**)]
 //like the Message here.

    public class DeBugInfo : System.Attribute
{
private int bugNo;
private string developer;
private string lastReview;
public string message;
public DeBugInfo(int bg, string dev, string d)
  {
   this.bugNo = bg;
   this.developer = dev;
   this.lastReview = d;
  }
  public int BugNo
 {
 get
 {
 return bugNo;
 }

public string Developer
{
get
{
 return developer;
 }
 }
 public string LastReview
{
get 
{
return lastReview;
}

public string Message
{
 get
{
 return message;
 }
  set
  {
    message = value;
  }
 } 




 //////////////////////////

屬性語法與常規C#代碼有點不同。 在常規C#中,如果您手動創建該對象,則類似於對象初始值設定項:

var obj = new DeBugInfo(45, "Zara Ali", "12/8/2012") {
    Message = "Return type mismatch"
};

但是,實際上,屬性並沒有以這種方式實際實例化 ,至少在它們絕對需要之前是這樣。 屬性實際上是標記在IL中的原始元數據,包括:

  • 構造函數標記
  • 構造函數的參數,由簡單值組成
  • 附加屬性/字段分配映射和相應的簡單值

實際上,您可以檢查所有這些信息,而無需實際創建該類型的實例。 但是如果你使用Attribute.GetAttributes等,它會找出它代表什么,並且基本上在運行時應用構造函數和映射。

有關完整示例:

using System;

class DeBugInfoAttribute : Attribute
{
    public string Message { get; set; }
    public DeBugInfoAttribute(int i, string j, string k)
    {
        // to show we never get here!
        throw new NotImplementedException();
    }
}

[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
static class Program
{
    static void Main()
    {
        // this doesn't create the attribute, so no exception
        foreach (var data in typeof(Program).GetCustomAttributesData())
        {
            Console.WriteLine(data.AttributeType.Name);
            var parameters = data.Constructor.GetParameters();
            int i = 0;
            foreach (var arg in data.ConstructorArguments)
            {
                Console.WriteLine("{0}: {1}",
                    parameters[i++].Name,
                    arg.Value);
            }
            foreach (var binding in data.NamedArguments)
            {
                Console.WriteLine("{0}: {1}",
                    binding.MemberInfo.Name,
                    binding.TypedValue);
            }
        }
        // but this does: BOOM!
        var attribs = Attribute.GetCustomAttributes(typeof(Program));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM