亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

自定義屬性的構造函數何時運行?

自定義屬性的構造函數何時運行?

瀟湘沐 2019-11-19 11:11:52
什么時候運行?它是否對我應用它的每個對象都運行一次,還是只運行一次?它可以做任何事情,或者其動作受到限制嗎?
查看完整描述

3 回答

?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

在屬性構造函數內設置調試器斷點,并編寫一些反射代碼以讀取那些屬性。您會注意到,只有從relfection API返回屬性對象后,才能創建屬性對象。屬性是每個類的。它們是元數據的一部分。


看看這個:


Program.cs

using System;

using System.Linq;

[My(15)]

class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine("Program started");

        var ats =

            from a in typeof(Program).GetCustomAttributes(typeof(MyAttribute), true)

            let a2 = a as MyAttribute

            where a2 != null

            select a2;


        foreach(var a in ats)

            Console.WriteLine(a.Value);


        Console.WriteLine("Program ended");

        Console.ReadLine();

    }

}

MyAttribute.cs

using System;

[AttributeUsage(validOn : AttributeTargets.Class)]

public class MyAttribute : Attribute

{

    public MyAttribute(int x)

    {

        Console.WriteLine("MyAttribute created with {0}.", x);

        Value = x;

    }


    public int Value { get; private set; }    

}

結果

Program started

MyAttribute created with 15.

15

Program ended

但不必擔心屬性構造函數的性能。它們是反思的最快部分:-P


查看完整回答
反對 回復 2019-11-19
  • 3 回答
  • 0 關注
  • 520 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號