![](/img/trans.png)
[英]How can i pick the comma separated attribute value in xml one by one as loop in c#
[英]How to pass comma separated value in attribute when input parameter is enum in c#
我有一個自定義屬性,如下所示,
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class SetValForAll : Attribute
{
public string Limit { get; set; }
public SetValForAll(string limit)
{
Limit = limit;
}
}
使用此屬性(SetValForAll)時,我想使用一個枚舉傳遞限制值,而不是單個值,而是枚舉的逗號分隔值。
我的枚舉如下所示,
public enum LimitEnum
{
Initiated,
InProcess,
Done
}
如果我在任何類型中應用該屬性,我期望枚舉的逗號分隔值(例如“Initiated,InProcess”)將在屬性中收到
我嘗試了下面的一段代碼,但它顯示錯誤。 如何使用屬性級別的枚舉來傳遞逗號分隔值?
[SetValForAll(nameof(LimitEnum.Initiated, LimitEnum.InProcess))]
public class UsingTheAttributeHere
{
}
您可以使用 Flags 枚舉來執行此操作。 例如
[Flags]
public enum LimitEnum
{
Initiated = 1,
InProcess = 2,
Done = 4
}
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class SetValForAll : Attribute
{
public LimitEnum Limit { get; set; }
public SetValForAll(LimitEnum limit)
{
Limit = limit;
}
}
[SetValForAll(LimitEnum.Initiated | LimitEnum.InProcess)]
public class UsingTheAttributeHere
{
}
如果您真的想要屬性中的字符串,可以使用字符串插值。
[SetValForAll($"{nameof(LimitEnum.Initiated)},{nameof(LimitEnum.InProcess)}")]
但是,如果接收端無論如何都要將這些讀取為枚舉值,那么最好使用Flags
枚舉並將 OR'ed 值傳遞給屬性,就像在 David Browne 的回答中一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.