简体   繁体   English

C#将类属性名称作为字符串参数传递

[英]C# Passing a Class Property Name as String Parameter

I know there might be a better way to do this, but I am kind of stumped. 我知道可能会有更好的方法来执行此操作,但我有些沮丧。

I have a static class defined as below: 我有一个静态类定义如下:

public static class ShuttleState
{
        public static readonly string Item1 = "VALUE MAY COME FROM CONFIG";
        public static readonly string Item2 = "VALUE MAY BE DEFINED DIFFERENTLY";
        public static readonly string Item3 = ConfigurationManager.AppSettings["Item3"];
}

Now I have a function where I am passing the name of the property, like below: 现在,我有了一个传递属性名称的函数,如下所示:

public bool Test(string itemName)
{
    bool isTest = false;
    var qry = (from a in this.Context.MyTable
                         select a).FirstOrDefault();

    switch(itemName)
    {
        case "Item1"
            isTest = (qry == null) ? false : (String.Compare(qry.TestItem, ShuttleState.Item1, true) == 0);
            break;

        case "Item2"
            isTest = (qry == null) ? false : (String.Compare(qry.TestItem, ShuttleState.Item2, true) == 0);
            break;

        case "Item3"
            isTest = (qry == null) ? false : (String.Compare(qry.TestItem, ShuttleState.Item3, true) == 0);
            break;
    }

    return isTest;
}

So how can I pass the parameter as property name so that I could simply do: 因此,如何将参数作为属性名称传递,这样我就可以做到:

isTest = (qry == null) ? false : (String.Compare(qry.TestItem, ShuttleState.[itemName], true) == 0);

Like use the function 喜欢使用功能

bool myTest = Test("Item1");

Any insight appreciated. 任何见解表示赞赏。 Thanks. 谢谢。

Update: A lot has posted to simply resolve the issue via the ConfigurationManager. 更新:发布了很多内容,只是为了通过ConfigurationManager解决问题。 Note that I only showed that as partial example, as the static class (including the values derived) are all over the place. 请注意,我仅以局部示例为例,因为静态类(包括派生的值)到处都是。 At the moment, I could only peruse the values as defined in the static class. 目前,我只能细读静态类中定义的值。

For those who might stumble on this, I took cue from Valentin to utilize dictionary and still peruse the static class. 对于那些可能会迷失方向的人,我从瓦伦丁(Valentin)那里学到了利用字典的提示,但仍然细读静态类。

My code as below: 我的代码如下:

public static class DictionaryOfShuttleState
{
  static Dictionary<string, string> _dict = new Dictionary<string, string>
  {
    {"Item1", ShuttleState.Item1},
    {"Item2", ShuttleState.Item2},
    {"Item3", ShuttleState.Item3}
  };

  public static string GetDictionaryValue(string keyValue)
  {
    string result;
    if(_dict.TryGetValue(keyValue, out result)
    {
      return result;
    }
    else
    {
      return String.Empty
    }

  }
}

And I am using it as follows: 我使用它如下:

string testValue = DictionaryOfShuttleState.GetDictionaryValue(itemName);
isTest = (qry == null) ? false : (String.Compare(qry.TestItem, testValue, true) == 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM