gpt4 book ai didi

c# - 在 C# 中有类似 Python 的 getattr() 的东西吗?

转载 作者:太空狗 更新时间:2023-10-29 17:31:47 24 4
gpt4 key购买 nike

有没有类似Python's getattr()的东西在 C# 中?我想通过读取一个列表来创建一个窗口,该列表包含要放在窗口上的控件的名称。

最佳答案

还有Type.InvokeMember .

public static class ReflectionExt
{
public static object GetAttr(this object obj, string name)
{
Type type = obj.GetType();
BindingFlags flags = BindingFlags.Instance |
BindingFlags.Public |
BindingFlags.GetProperty;

return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null);
}
}

可以这样使用:

object value = ReflectionExt.GetAttr(obj, "PropertyName");

或(作为扩展方法):

object value = obj.GetAttr("PropertyName");

关于c# - 在 C# 中有类似 Python 的 getattr() 的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/138045/

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