说我有一个属性限制的财产分配给一组在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