简体   繁体   中英

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. 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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