[英]How to create a Lazy property passing a string property of <this> class as parameter to it in C#?
[英]C# Passing a Class Property Name as String Parameter
我知道可能会有更好的方法来执行此操作,但我有些沮丧。
我有一个静态类定义如下:
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"];
}
现在,我有了一个传递属性名称的函数,如下所示:
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;
}
因此,如何将参数作为属性名称传递,这样我就可以做到:
isTest = (qry == null) ? false : (String.Compare(qry.TestItem, ShuttleState.[itemName], true) == 0);
喜欢使用功能
bool myTest = Test("Item1");
任何见解表示赞赏。 谢谢。
更新:发布了很多内容,只是为了通过ConfigurationManager解决问题。 请注意,我仅以局部示例为例,因为静态类(包括派生的值)到处都是。 目前,我只能细读静态类中定义的值。
对于那些可能会迷失方向的人,我从瓦伦丁(Valentin)那里学到了利用字典的提示,但仍然细读静态类。
我的代码如下:
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
}
}
}
我使用它如下:
string testValue = DictionaryOfShuttleState.GetDictionaryValue(itemName);
isTest = (qry == null) ? false : (String.Compare(qry.TestItem, testValue, true) == 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.