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 + + const在c#中?
- 5. Getattr在Python中的封装
- 6. 在c中有没有像c()中的clock()函数?
- 7. 有没有setTimeout(像)在objective-c
- 8. 有没有像Python那样的readability.js?
- 9. Python有没有像Ruby的雾?
- 10. 有没有像Python的dkpro实验室?
- 11. 有没有像python中的所有类似dict的方法?
- 12. 在Python中切片清单:有没有像-0的东西?
- 13. 有没有像在像.NET
- 14. 有没有在Python
- 15. 有没有C#等同于Python的unhexlify?
- 16. 在c#中有没有像tadvgrid的delphi的网格?
- 17. C有没有像PHP ob_start的东西?
- 18. 有没有像样的Websocket C#实现?
- 19. 有没有像getdelim是C++的函数?
- 20. 在c#中有没有像java的Character.digit(char ch,int radix)?
- 21. python combined setattr和getattr
- 22. Python单元测试有没有像'autotest'?
- 23. Objective-C中有没有像SHA1CryptoServiceProvider(即C#)的东西?
- 24. 在Python中使用getattr调用方法
- 25. python,在getattr中使用两个变量?
- 26. 没有在Python
- 27. Python动态调用; getattr的?
- 28. Python的GETATTR调用函数
- 29. 有没有像python中的PAM一样的模块?
- 30. 有没有像Python中设置的数组的一些方法?