我有一個帶有常量的靜態類。我正在尋找選項來創建一個方法,該方法將字典作爲參數,並將該關鍵字作爲靜態類中的常量之一。以下是帶有常量的靜態類。
將靜態類常量作爲數據類型執行
1
A
回答
2
儘管這已經被回答了,還有一個辦法,像這樣:
public class MyOwnEnum
{
public string Value { get; private set; }
private MyOwnEnum(string value)
{
Value = value;
}
public static readonly MyOwnEnum FirstName = new MyOwnEnum("Firstname");
public static readonly MyOwnEnum LastName = new MyOwnEnum("LastName");
}
它的行爲與Enum相同,可以在您的代碼中使用相同的語法。我不能讚揚誰提出了它,但我相信我在搜索具有多個值的Enums時遇到了它。
0
用繩子,你不能強制事實密鑰來自有限集的編譯時間。
改爲使用枚舉或自定義類(可能將其隱式轉換爲字符串)。
3
從它的聲音中,Enum會更適合你想要做的事情。
public enum MyConstants
{
FirstName,
LastName,
Title
}
public void CreateMe(Dictionary<MyConstants, string> propertyBag)
{
...
}
修訂
您可以用屬性結合這對每個枚舉一個特定的字符串,像這樣聯想:
public enum PropertyNames
{
[Description("first_name")]
FirstName,
[Description("last_name")]
LastName,
[Description("title")]
Title
}
與每個枚舉值相關聯的每個描述屬性的價值可能很容易通過擴展方法抓取,如下所示:
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fieldInfo.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
然後在你的「CreateMe」 - 方法,你可以做類似的事情這讓每個字典條目的說明和值:
void CreateMe(Dictionary<PropertyNames, string> propertyBag)
{
foreach (var propertyPair in propertyBag)
{
string propertyName = propertyPair.Key.GetDescription();
string propertyValue = propertyPair.Value;
}
}
相關問題
- 1. 靜態斷言檢查靜態常量類數據成員?
- 2. 傳遞類型變量作爲一般類型參數爲靜態
- 3. 靜態常量定義類
- 4. 類中靜態常量ODR
- 5. 聲明非靜態常量數組作爲類成員
- 6. 將數組作爲靜態類屬性的奇怪行爲
- 7. 模板類中的靜態常量類型
- 8. 使用靜態類作爲變量
- 9. 類作爲靜態變量的容器
- 10. 作爲類型參數的非靜態內部類名稱
- 11. 將大量數據保存爲靜態類效率不高嗎?
- 12. 在swift類的靜態函數中訪問非靜態常量
- 13. 作爲類的靜態屬性的常量內存符號
- 14. 如何遍歷類的靜態數據成員 - 使用變量作爲類名?
- 15. C# - 靜態類型不能用作類型參數
- 16. 片段作爲靜態類
- 17. 靜態類中的靜態變量和非靜態類中的靜態變量
- 18. 靜態/非靜態內部類:類型參數T隱藏類型T
- 19. FieldOperator類不包含靜態常量
- 20. 靜態常量類成員聲明
- 21. C++類中的靜態常量成員
- 22. Python靜態類型?
- 23. 將常規類成員轉換爲靜態類成員
- 24. 常量在Haskell代數數據類型
- 25. 靜態類或實例作爲參數?
- 26. 類型類多態數據類型
- 27. 用作模板的類中的靜態常量變量
- 28. 使用靜態常量+作爲常量數組邊界
- 29. 將日期數據類型轉換爲日期時間數據類型並添加靜態時間
- 30. C# - 將靜態類初始化爲非靜態類?
你的解釋不清楚。 – TomTom
我同意@TomTom,根據所提供的信息,您正試圖完成的任務令人困惑。 – mituw16
你只能使用反射來做到這一點。 –