![](/img/trans.png)
[英]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.