加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 变量可以用作属性吗?

发布时间:2020-12-15 22:27:45 所属栏目:百科 来源:网络整理
导读:我想做这样的事情: string currPanel = "Panel";currPanel += ".Visible" 现在,此时我有一个字符串变量,其属性名称只接受布尔值.我可以做一些这样的事情: data type currPanel = true; 所以实际属性Panel1.Visible接受它没有任何错误? 解决方法 支持属性
我想做这样的事情:

string currPanel = "Panel";
currPanel += ".Visible"

现在,此时我有一个字符串变量,其属性名称只接受布尔值.我可以做一些这样的事情:

<data type> currPanel = true;

所以实际属性Panel1.Visible接受它没有任何错误?

解决方法

支持属性和字段,但仅支持实例:

public static void SetValue(object obj,string name,object value)
{
    string[] parts = name.Split('.');

    if (parts.Length == 0)
    {
        throw new ArgumentException("name");
    }

    PropertyInfo property = null;
    FieldInfo field = null;
    object current = obj;

    for (int i = 0; i < parts.Length; i++)
    {
        if (current == null)
        {
            throw new ArgumentNullException("obj");
        }

        string part = parts[i];

        Type type = current.GetType();

        property = type.GetProperty(part,BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (property != null)
        {
            field = null;

            if (i + 1 != parts.Length)
            {
                current = property.GetValue(current);
            }

            continue;
        }

        field = type.GetField(part,BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        if (field != null)
        {
            property = null;

            if (i + 1 != parts.Length)
            {
                current = field.GetValue(current);
            }

            continue;
        }

        throw new ArgumentException("name");
    }

    if (current == null)
    {
        throw new ArgumentNullException("obj");
    }

    if (property != null)
    {
        property.SetValue(current,value);
    } 
    else if (field != null)
    {
        field.SetValue(current,value);
    }
}

使用示例:

public class Panel
{
    public bool Visible { get; set; }
}

public class MyTest
{
    public Panel Panel1 = new Panel();

    public void Do()
    {
        string currPanel = "Panel1";
        currPanel += ".Visible";

        SetValue(this,currPanel,true);
    }
}

var mytest = new MyTest();
mytest.Do();

请注意,我不支持索引器(如Panel1 [5] .Something).支持int索引器是可行的(但另外30行代码).支持not-int索引器(如[“Hello”])或多键索引器(如[1,2])会非常困难.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读