C#中的Eval函数 [英] Eval Function in C#

查看:289
本文介绍了C#中的Eval函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个AppSettings类,其中包含许多字符串。

I have a AppSettings class which contains a number of strings in it.

  public class AppSettings
    {
        public AppSettings();

        public static string 1stString{ get; }
        public static string 2ndString{ get; }
        public static string 3rdString{ get; }
    )


//Call the AppSettings

字符串= AppSettings.1stString ;

string first = AppSettings.1stString;

我将给出任何字符串作为变量"AnyString",它可以是"1stString","2ndString"和"2ndString"。等等,我可以做以下事情吗?基本上,如何评估变量AnyString?

I will be given any of strings as an variable "AnyString", which may be"1stString", "2ndString" and etc. , can I do something like the following? Basically, how to I evaluate the variable AnyString?

string first = AppSettings[AnyString];

or 

string first = AppSettings.eval[AnyString];

提前致谢。非常感谢您的帮助!

Thanks in advance. And your help would be greatly appreciated!




推荐答案

这是一种使用反射的方法;

Here is a way using reflection;

class Program
{
	class AppSettings
	{
		public string Setting1;
		public string Setting2;
		public string Setting3;
	}

	static void Main(string[] args)
	{
		AppSettings s = new AppSettings();
		s.Setting1 = "Value1";
		s.Setting2 = "Value2";
		s.Setting3 = "Value3";

		Type appSettingsTypeInfo = typeof(AppSettings);
		FieldInfo[] fields = appSettingsTypeInfo.GetFields();

		string whichField = "Setting2";

		string value = (string)(fields.First(f => f.Name == whichField).GetValue(s));
		Console.WriteLine(value);
		Console.ReadKey();
	}
}


此示例输出"Value2"到控制台。

This example outputs "Value2" to the console.


这篇关于C#中的Eval函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆