2016-03-08 60 views
1

我有一个带有常量的静态类。我正在寻找选项来创建一个方法,该方法将字典作为参数,并将该关键字作为静态类中的常量之一。以下是带有常量的静态类。
enter image description here将静态类常量作为数据类型执行

这里就是我试图做 enter image description here

这里是什么,我想执行 enter image description here

+0

你的解释不清楚。 – TomTom

+0

我同意@TomTom,根据所提供的信息,您正试图完成的任务令人困惑。 – mituw16

+0

你只能使用反射来做到这一点。 –

回答

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; 
    } 
} 
+2

枚举不强制该变量的值实际上是一个枚举值,它们只是幻想的整数常量。要检查值是否实际上在枚举中定义,请使用'Enum.IsDefined(...)'方法。 –

+0

这里是catch,常量的名称与值不一样。不像我的例子。我需要传递字典中的“first_name”,但用户应该能够使用常量MyConstants.FirstName。基本上。我的常数名称与其价值不同。这就是为什么枚举不起作用。感谢你的帮助。 – Rishab

+0

@Shazi,我用屏幕截图更新了我的最初问题,我的常量实际上看起来像 – Rishab