C#中有没有类似Python's getattr()的东西?我想通过阅读一个列表来创建一个窗口,其中包含要放在窗口上的控件的名称。在C#中有没有像Python的getattr()?
13
A
回答
9
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");
3
为此使用反射。
Type.GetProperty()
和Type.GetProperties()
每个返回PropertyInfo
实例,它们可用于读取对象的属性值。
var result = typeof(DateTime).GetProperty("Year").GetValue(dt, null)
Type.GetMethod()
和Type.GetMethods()
每个返回MethodInfo
情况下,其可用于在对象上执行的方法。
var result = typeof(DateTime).GetMethod("ToLongDateString").Invoke(dt, null);
如果你不一定知道的类型(这将是一点点奇怪,如果你新的属性名),比你可以做这样的事情为好。
var result = dt.GetType().GetProperty("Year").Invoke(dt, null);
1
是的,你可以做到这一点...
typeof(YourObjectType).GetProperty("PropertyName").GetValue(instanceObjectToGetPropFrom, null);
0
有可以使用object.GetType创建的System.Reflection.PropertyInfo类()。GetProperties中()。这可以用来使用字符串探测对象的属性。 (类似的方法存在对象方法,字段等)
我不认为这会帮助你实现你的目标。你应该直接创建和操作对象。例如,控件具有可以设置的Name属性。
相关问题
- 1. 有没有像C++的Python的StringIO/CStringIO?
- 2. getattr()没有'类对象'
- 3. C有没有像IDLE(python)的东西?
- 4. C++等价的Python GETATTR
- 5. 有没有像c + + const在c#中?
- 6. Getattr在Python中的封装
- 7. 为什么Python没有内置的混合getattr + __getitem__?
- 8. 有没有像C中的BinaryWriter?
- 9. 在c中有没有像c()中的clock()函数?
- 10. 有没有像Python中的`lag.plot1`这样的Python中的方法?
- 11. getattr(self,'__a')和self .__ a在Python中有什么区别?
- 12. AttributeError的:“诠释”对象有没有属性“GETATTR”
- 13. 在python熊猫中,有没有像qbar中的xbar?
- 14. 有没有setTimeout(像)在objective-c
- 15. Python有没有像Ruby的雾?
- 16. 有没有像Python的dkpro实验室?
- 17. 有没有像j2me的Python解析器?
- 18. 有没有像Python那样的readability.js?
- 19. 有没有像Python导出的东西?
- 20. 在C#中有没有像vb中的任何app.config文件?
- 21. 有没有像python中的所有类似dict的方法?
- 22. 在Python中切片清单:有没有像-0的东西?
- 23. 有没有在Python
- 24. 有没有C#等同于Python的unhexlify?
- 25. 有没有像在像.NET
- 26. 在c#中有没有像tadvgrid的delphi的网格?
- 27. 有没有像样的Websocket C#实现?
- 28. 有没有像getdelim是C++的函数?
- 29. C有没有像PHP ob_start的东西?
- 30. python combined setattr和getattr