[英]C# How do I use a variable in a Linq select statement using Query Syntax
[英]How do I select a C# variable using a string
我有一個字符串用戶設置,並希望在我的C#Windows應用程序啟動期間選擇具有相同名稱的特定變量。
例如
我有一個名為UserSelectedInt的用戶設置(字符串),當前設置為'MyTwo'。 (請注意,我的變量實際上比整數更復雜,我只是用它們作為例子。)
public static int MyOne = 12345;
public static int MyTwo = 54321;
public static int MyThree = 33333;
public int myInt = SelectMyVariableUsing(MyApp.Settings.Default.UserSelectedInt)
用戶可能在上次關閉應用時選擇了“MyTwo”,因此這是我想在啟動時選擇的變量。 我希望我有意義。
請有人告訴我如何實現這一目標?
謝謝
使用Dictionary<string, int>
。 這允許您為一些字符串分配一個整數值。 如果字符串是用戶輸入,則需要在嘗試檢索相應的整數之前檢查它是否有效。
聽起來你正在嘗試實現提供者模式 。 你可能會發現使用它是一個更好的機制供你使用,特別是你說它比使用int更復雜。
在您的代碼中,您將使用MyApp.Settings.Default.UserSelectedInt
設置引用特定提供程序。
我會說在架構上這將是一個比其他一些建議的答案更好的機制。
最簡單的方法可能就是使用GetField。
使用您的示例只需將最后一行更改為:
var selectedField = MyApp.Settings.Default.UserSelectedInt
public int myInt = (int) GetType().GetField(selectedField).GetValue(this);
如果字段或類是靜態的,則語法應為:
var selectedField = MyApp.Settings.Default.UserSelectedInt
public int myInt = (int)typeof(YourClass).GetField(selectedField).GetValue(null);
有關詳細信息,請參閱http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.getvalue.aspx 。
// enumerate your list of property names (perhaps from a file)
var settings = new List<string>();
settings.Add("MyOne");
settings.Add("MyTwo");
settings.Add("MyThree");
var settingMap = new Dictionary<string, int>();
int value = 0;
foreach (var name in settings)
{
try
{
// try to parse the setting as an integer
if (Int32.TryParse((string)Properties.Settings.Default[name], out value))
{
// add map property name to value if successful
settingMap.Add(name, value);
}
else
{
// alert if we were unable to parse the setting
Console.WriteLine(String.Format("The settings property \"{0}\" is not a valid type!", name));
}
}
catch (SettingsPropertyNotFoundException ex)
{
// alert if the setting name could not be found
Console.WriteLine(ex.Message);
}
}
但是,如果你進入變量列表為巨大的階段,那么我可能會看到實際通過某種形式的XML解析直接訪問屬性文件。
應該可以用反射
您也可以使用Hashtable 。
但是,從它的外觀來看,你真正想做的就是存儲用戶最后選擇的值,因此我可能只是將它作為字符串保存在UserSettings中然后在加載時我只是解析該值。
我希望我正在讀這個,但基本上,我覺得你想記住上次用戶選擇的價值。 由於應用程序將在此期間關閉,您將不得不將其存儲在某處。 也許在一個文件中。
對我而言,聽起來更像是應該使用枚舉而不是靜態變量,請考慮以下示例:
public enum MyVars
{
MyOne = 12345, MyTwo = 54321, MyThree = 33333
}
static void Main(string[] args)
{
Console.WriteLine(String.Format("Name:{0}, Val={1}", MyVars.MyOne.ToString(), (int)MyVars.MyOne ));
Console.ReadKey();
}
,它將輸出“Name:MyOne,Val = 12345”,通過枚舉,您可以輕松找出變量的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.