【问题标题】:Use string as public string name?使用字符串作为公共字符串名称?
【发布时间】:2011-07-13 19:52:22
【问题描述】:

我有文件:dvars.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GSM
{
    public static class dvar
    {
            static int _pspeed = 2;

            public static int pspeed
            {
                get
                {
                    return _pspeed;
                }
                set
                {
                    _pspeed = value;
                }
            }
    }

}

例如,我希望能够使用字符串来定义它(在不同的文件中,我想使用字符串作为变量名来设置 dvar.pspeed):

string mystring = "pspeed";
dvar.mystring = 1;

有人知道我该怎么做吗?

【问题讨论】:

  • 问题:此时您会期望 dvar.pspeed == 1 吗?问题是您没有设置变量名,而是设置了属性值。变量和属性是非常不同的动物。我认为您正在谈论为您的属性名称起别名。为什么要这样做?

标签: c# string class static public


【解决方案1】:

我想你可以使用反射来做到这一点。

String mystring = "pspeed";
PropertyInfo pi = typeof(dvar).GetProperty(mystring);
pi.SetValue(dvar, 1, new Object[0]);

【讨论】:

    【解决方案2】:

    您不能这样做,但是您可以使用索引器包装字典:

    public static class Dvar 
    {
        private static IDictionary<string, int> map = new Dictionary<string, int>();
    
        public static int this[string key]
        {
            get { return map[key]; }
            set { map[key] = value; }
        }
    }
    

    并像这样使用它:

    Dvar["pspeed"] = 1;
    

    【讨论】:

    • @Fraser - 是的,这也是可能的,如果他只有一个财产,那么你的答案更有可能是他想要的。
    【解决方案3】:

    您可以只使用 Int32.Prase() 方法或(如果您需要验证它,请使用 TryParse())。

    【讨论】:

    • 仅供参考:TryParse 不允许您将属性用作输出参数。
    • 我想使用字符串作为变量名来设置 dvar.pspeed
    猜你喜欢
    • 2017-05-08
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 2011-09-05
    • 1970-01-01
    • 2019-08-20
    • 2021-05-19
    相关资源
    最近更新 更多