简体   繁体   English

动态列出object的内容

[英]List content of an object dynamicly

There are two kinds of objects:有两种对象:

public class Toto
{
    String test1 = "";
    int test2 = 0;
}

public class Titi
{
    String testA = "";
    int testB = 0;
}

I would create a method which permit me to check dynamicly the content of any object.我将创建一个方法,允许我动态检查任何 object 的内容。 For example:例如:

public void checkDatas(Object o)

In this method, I would access to test1 and check its value, then test2, then testA, and testB.在这种方法中,我将访问 test1 并检查它的值,然后是 test2,然后是 testA 和 testB。 Like something like this (Object) Object.getMember(new Toto(), "test1")像这样的东西(对象)Object.getMember(new Toto(), "test1")

I found some explanations with the reflection process but nothing works.我在反射过程中找到了一些解释,但没有任何效果。

Someone have an idea?有人有想法吗?

Thanks in advance.提前致谢。

You can use reflection to read the members of (unknown) objects, eg:您可以使用反射来读取(未知)对象的成员,例如:

public class Toto
{
    String test1 = "aaa";
    int test2 = 0;
}

// -------------

Toto t = new Toto();

var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
foreach (FieldInfo field in t.GetType().GetFields(flags))
{
    Console.WriteLine(field.Name + " : " + field.GetValue(t));
}

This produces the following output:这将产生以下 output:

test1 : aaa
test2 : 0

Note: if your classes have private fields, then you must specify the correct BindingFlags when calling Type.GetFields() , as shown above.注意:如果您的类有私有字段,那么您必须在调用Type.GetFields()时指定正确的BindingFlags ,如上所示。

You can do something like this, but without knowing more about what 'checking each member' is, I can't really help you more:你可以做这样的事情,但如果不知道更多关于“检查每个成员”是什么,我真的不能帮助你更多:

public void CheckMembers(object o)
{
    foreach(var member in o.GetType().GetFields())
    {
        object value = member.GetValue(o);
    }
}

I really can't tell why you want something like this, please provide that information if you have it.我真的不知道你为什么想要这样的东西,如果你有,请提供该信息。 But can't you do something like this:但是你不能做这样的事情:

var type = o.GetType();
var members = type.GetMembers(BindingFlags.NonPublic|BindingFlags.Public);
foreach(var member in members)
{
    var field = type.GetField(member.Name);
    Console.WriteLine(field.GetValue(o));
}

UPDATE: Use MemberInfo instead of PropertyInfo, and you still should provide us with the information about what you are doing.更新:使用 MemberInfo 而不是 PropertyInfo,您仍然应该向我们提供有关您在做什么的信息。

Try access instanses in this way instead:尝试以这种方式访问实例:

public void checkDatas(Object o)
{
    if (o is Toto)
    {
       (o as Toto).test1 = 0;
    }

    if (o is Titi)
    {
       (o as Titi).testA = "";
    }
}

Note that I assume that the fields are public.请注意,我假设这些字段是公开的。

While you could achieve this reflection using string value = typeof(Toto).GetField("test1").GetValue(instance);虽然您可以使用string value = typeof(Toto).GetField("test1").GetValue(instance); if you know the types, it's much more efficient just to use to method overloads:如果您知道类型,那么仅使用方法重载会更有效:

public void CheckObject(Toto toto) { }
public void CheckObject(Titi titi) { }

Or better yet, have both objects conform to an interface, say ICheckable , and that way you only need implement one method:或者更好的是,让两个对象都符合一个接口,比如ICheckable ,这样你只需要实现一个方法:

public void CheckObject(ICheckable checkable);

First of all, Object Oriented programming, an object would not allow you any external sources to view its private fields.首先,Object 面向编程,object 不允许您任何外部资源查看其私有字段。

For similar needs, for example to express the content of an object ToString() method can be overridden.对于类似的需求,例如表达 object ToString() 方法的内容,可以重写。 Remember the object has to decide on which value to expose.请记住 object 必须决定要公开哪个值。

So in your case you may override ToString like this.因此,在您的情况下,您可以像这样覆盖 ToString 。

public override string ToString()
{
     return String.Format("Value of test1={0}\nValue of test2={1}", test1, test2);
}

Or try to implement an interface as with method like RevealValues().或者尝试像 RevealValues() 这样的方法来实现接口。 Implement this interface in every class that you might want to examine later on.在您以后可能要检查的每个 class 中实现此接口。

First of all, I would try to implement some commonality in the objects you want to check.首先,我会尝试在您要检查的对象中实现一些共性。

For example, is it necessary that Toto defines test1 while Titi defines testA?例如,是否需要 Toto 定义 test1 而 Titi 定义 testA? Would it be possible if Toto and Titi defined both test1?如果 Toto 和 Titi 都定义了 test1,有可能吗? That way you would be able to create and common interface for both:这样您就可以为两者创建通用接口:

public class Toto
{
    private string test1 = "Hello from Toto object"; 
    public string Test1 { get { return this.test1; } }
}

public class Titi
{
    private string test1 = "Hello from Titi object"; 
    public string Test1 { get { return this.test1; } }
}

Now you can define a common interface:现在您可以定义一个通用接口:

public interface ICheerfulObject
{
    string Test1 { get; }
}

Make both your classes implement this interface like so:让你的两个类都实现这个接口,如下所示:

public class Toto: ICheerfulObject
{
     ....
}

pulbic class Titi: ICheerfulObject
{
     ....
}

And you can then do:然后你可以这样做:

public void CheckData(ICheerfulObject o)
{
    string data = o.Test1;
}

If this scenario is not valid and you really need to use Reflection try the following:如果这种情况无效并且您确实需要使用反射,请尝试以下操作:

 public void CheckData(object o)
 {
     PropertyInfo property = o.GetType().GetProperty("Test1");  //Get used to using public properties.
     string data = (string)property.GetValue(o, null);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Unity将内容动态添加到NGUI网格 - Unity add content dynamicly to NGUI grid 动态转换类型对象到类型(某些类) - Dynamicly Converting Type Object to Type (Some Class) 如何动态传递数据到选择列表? - How to dynamicly pass data to select list? 检测并动态加载已安装的Microsoft Word对象库 - Detecting and dynamicly loading the installed Microsoft Word Object Library 为什么动态无法在动态构建的对象上调用方法? - Why does dynamic fail to invoke methods on my dynamicly built object? 当需要动态调整多维清单时,我将使用什么? - What would I use when in need of a dynamicly adjusting multidemnsional list? 从List &lt;&gt;中动态删除并添加另一个字母,并保持字母顺序 - Dynamicly remove and add another letter from a List<> keeping alphabetical order 检查列表中的对象是否具有特定的字段内容 - Check if object in list has specific field content ASP.NET:动态添加Webpanel时,获取&#39;currentStyle&#39;为null或不是对象 - ASP.NET : getting 'currentStyle' is null or not an object when adding webpanel dynamicly 在c#dotnet核心中从JSON格式动态创建对象的方法 - way to dynamicly create object from JSON format in c# dotnet core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM