gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:41:57 25 4
gpt4 key购买 nike

我想做这样的事情:

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

此时,我有一个字符串变量,其名称为只接受 bool 值的属性。我可以做一些这样的事情吗:

<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])很难。

关于c# - 变量可以用作属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35507581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com