簡體   English   中英

如何在c#中訪問屬性屬性中的類變量?

[英]How can I access to class variable in property attribute in c#?

我為properygrid定義了一個屬性,該屬性的價值是創建者的集合。 我定義了CreatorsEditor類。 在此類中,我使用HumanRolesCode變量。 如何在屬性的屬性中訪問此變量以獲取設置值。 我想更改HumanRolesCode值。 例如: [Editor(typeof(CreatorsEditor(HumanRolesCode = 10))]

我的代碼是:

[Editor(typeof(CreatorsEditor), typeof(UITypeEditor))]
public string Creators { get; set; }
//-------------------------------------

public class CreatorsEditor : UITypeEditor
{
    public static int HumanRolesCode;

    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }

    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        IWindowsFormsEditorService svc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
        if (svc != null)
        {
            CreatorFrm.HumanRoleCode = HumanRolesCode;
            CreatorFrm Frm = new CreatorFrm();
            if (svc.ShowDialog(Frm) == System.Windows.Forms.DialogResult.OK)
            {
                string HumanNames = "";
                for (int i = 0; i < Frm.DgvCreator.Rows.Count; i++)
                    if (Boolean.Parse(Frm.DgvCreator[0, i].Value.ToString()) == true)
                        HumanNames += Frm.DgvCreator[2, i].Value.ToString() + " , ";
                if (!string.IsNullOrEmpty(HumanNames))
                    HumanNames = HumanNames.Substring(0, HumanNames.Length - 3);
                return HumanNames;
            }
        }
        return value;
    }
}

屬性參數必須是屬性參數類型的常量表達式,typeof表達式或數組創建表達式。

分配一些值似乎是不可能的,並且通常使一些運行時代碼(方法\\屬性)由custom屬性的聲明執行。

定制屬性只是將附加信息與目標關聯的一種方法,編譯器只是將附加信息添加到元數據中……當您想在編譯時進行更改時,該變量僅在運行時存在。

此外,自定義屬性的實例不會創建,除非您使用反射來檢索它(再次-在運行時,而聲明在編譯時)。

傑弗里·里希特(Jeffrey Richter)的書“通過C#進行CLR”中有一章關於自定義屬性。 我建議您閱讀它,以了解自定義屬性的行為,使用它們的可能操作以及如何使用它們。

暫無
暫無

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

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