簡體   English   中英

類實例屬性可以作為屬性中的值

[英]Possible for a class instance property as a value in an attribute

我有一個靜態類,其中包含我的類的很多實例。 MyThing的所有實例均在此處定義。

public static class AllMyThings
{
    public static MyThing first { get; } = new MyThing(name = "Foo", otherProperty = "1");
    public static MyThing second { get; } = new MyThing(name = "Bar", otherProperty = "50");
    ...
}

在代碼的其他地方,我有一些要向其中添加屬性的方法。 我希望這些屬性的值來自這些類實例。 像這樣

[MyAttribute(AllMyThings.first.name)
public void MyMethod()

這樣做給我錯誤

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

我不能first將其定義為const,因為它是MyThing的實例。 我想做這項工作的唯一方法是擁有這樣的東西

public static class AllMyThings
    {
        public const string firstName = "Foo";
        public const string secondName = "Bar";

        public static MyThing first { get; } = new MyThing(name = firstName, otherProperty = "1");
        public static MyThing second { get; } = new MyThing(name = secondName, otherProperty = "50");
    }

[MyAttribute(AllMyThings.firstName)
public void MyMethod()

但我想避免代碼的其他部分現在必須與firstfirstName ,而不是僅與first

還有其他選擇嗎?

有一種方法,但是您必須為此使用反射。 這是屬性:

[MyAttribute(typeof(AllMyThings), nameof(AllMyThings.first))
public void MyMethod()

現在,您的屬性可以正常編譯,但是為了獲取AllMyThings.first.name的值,您必須獲取AllMyThings的類型,按名稱查找靜態公共屬性,然后檢索該屬性值。

暫無
暫無

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

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