說我有一個屬性限制的財產分配給一組在C#中的常量
public string RestrictedString {get; set;}
,我有幾個靜態常量字符串定義
public const string String1 = "First String";
public const string String2 = "Second String";
有沒有辦法只允許RestrictedString要分配給String1還是String2?
說我有一個屬性限制的財產分配給一組在C#中的常量
public string RestrictedString {get; set;}
,我有幾個靜態常量字符串定義
public const string String1 = "First String";
public const string String2 = "Second String";
有沒有辦法只允許RestrictedString要分配給String1還是String2?
using System;
using System.ComponentModel;
using System.Reflection;
public static class Program
{
public const string String1 = "First String";
public const string String2 = "Second String";
public enum RestrictedStrings
{
[Description("First String")]
String1,
[Description("Second String")]
String2
}
public static string GetDescription(Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
{
return ((DescriptionAttribute)attrs[0]).Description;
}
}
return en.ToString();
}
public static void Main()
{
string description = Program.GetDescription(Program.RestrictedStrings.String1);
Console.WriteLine(description);
}
}
// Output: First String
希望這有助於。
從概念上講,你想要一個新類型,所以創建一個代表有效值的新類型。你的情況,你希望有隻爲你的類型兩種可能的有效值,因此構建的,不允許任何更多的構造:
public class SomeMeaningfulName
{
private SomeMeaningfulName(string value)
{
Value = value;
}
public string Value { get; }
public static SomeMeaningfulName String1 = new SomeMeaningfulName("First String");
public static SomeMeaningfulName String2 = new SomeMeaningfulName("Second String");
}
現在,您可以更改屬性的類型到新鍵入,並知道它只是這兩個值中的一個(可以從中獲取字符串值)。
爲什麼不把這個問題標記爲重複,如果你的答案與接受的答案類似[here](https://stackoverflow.com/questions/1851567/chow-to-use-enum-for-存儲串常數)? –
@BviLLe_Kid如果你發現一個重複的問題,你爲什麼不把這個問題標記爲重複的? – Servy
在我研究將常量變量存儲在枚舉中之前,我發佈了一個答案,當我遇到Description屬性時,該問題與您發佈的內容有相似的答案。 –
通過'DescriptionAttribute'使它成爲可枚舉的 –
我已經看到它完成的最好方法是通過類型安全的字符串枚舉模式。你可以看到實現細節[這裏](https://blog.falafel.com/introducing-type-safe-enum-pattern/) – Kolichikov
是的,你檢查Set上的值並拋出它是否不正確。如果你想要類型安全,每個字符串應該是某個基類的密封類。不,沒有任何方法可以真正阻止不允許的字符串,除非您在set和throw中檢查它們。即使枚舉也不易受攻擊,因爲您可以將任何適用值賦予枚舉,而不管它是否具有賦值。 'enum foo {bar = 1; } foo whoops =(foo)9001;'是完全有效的代碼。 – Will