Csharp/C#教程:在不知道免费精选名字大全的情况下获取对象的属性值?分享


在不知道免费精选名字大全的情况下获取对象的属性值?

class A { public string a { get; set; } --and so on-- //lets we have 30-50 class variables// } 

我知道它很糟糕。 但是我怎么能通过循环而不知道他们的免费精选名字大全只是通过对象或类的实例获得所有变量的值?

喜欢

 for(int i;i<30;i++) { variable[i] = object.? ; } 

使用reflection。

 typeof(A).GetFields() typeof(A).GetProperties() 

在您的示例中,您有一个字段而不是属性。 下面显示了如何遍历类型的所有成员的示例。 您可以使用FindMembers而不是GetMemebrs进行过滤

 public class Reflector { public void ShowMembers(object o) { Type type = o.GetType(); foreach (MemberInfo member in type.GetMembers()) { Console.WriteLine("{0} is a {1}", member.Name, member.MemberType); } } } 

针对按钮运行上面的代码,你得到类似的东西:

 ...skip... ManipulationDelta is a Event ManipulationInertiaStarting is a Event ManipulationBoundaryFeedback is a Event ManipulationCompleted is a Event IsDefaultProperty is a Field IsCancelProperty is a Field IsDefaultedProperty is a Field ... 

所以要明确一点:

 Public string a; 

是一个领域,而

 public string a { get; set; } 

将是一个财产。

我实际上没有回答这个问题。 这对我来说很聪明。

 public class Reflector { public void ShowMembers(object o) { Type type = o.GetType(); foreach (MemberInfo member in type.GetMembers()) { Console.WriteLine("{0} is a {1}", member.Name, member.MemberType); } } public void Set(object o, string fieldName, int val) { MemberInfo[] info = o.GetType().GetMember(fieldName); FieldInfo field = info[0] as FieldInfo; field.SetValue(o, val); } public int x; } 

如果我叫reflector.Set(reflector, "x", 10); 所以我自己调用Set,上面的方法会将值设置为10.如果要读取值,则为GetValue。

上述就是C#学习教程:在不知道免费精选名字大全的情况下获取对象的属性值?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/956974.html

(0)
上一篇 2021年11月21日
下一篇 2021年11月21日

精彩推荐