你如何修剪对象在C#.NET其基本对象? [英] How do you prune an object to its base object in C#.NET?

查看:130
本文介绍了你如何修剪对象在C#.NET其基本对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的方法:

public PrintObjectHierarchy(object o)
{
   Console.WriteLine(o.GetType.FullName);

   object baseObject = PruneObjectToItsBaseObject(o);
   if(!baseObject.GetType().Equals(typeof(object)))
       PrintObjectHierarchy(baseObject);
   else Console.WriteLine("System.Object");
}

例如,如果我写的:

class Form1 : Form
{
  static void Main()
  {
    Form1 f1 = new Form1();
    PrintObjectHierarchy(f1);
  }
}

然后,它应该打印对我来说:

Then it should print for me:

MyNamespace.Form1
System.Windows.Form
System.Windows.Forms.ContainerControl
/*and so so till...*/
System.Object

但unforunately,就算我投对象,其基本类型,C#多态性只是将限制其查看以基本类型和不返回真正的从参考一个真正的基本对象给我!让我们通过一个例子描述它;如果我有

But unforunately, even if I CAST object to its BaseType, "C# Polymorphism" just will limit its VIEW to the base type and does not return a REAL reference from a REAL base object to me! Let's describe it by an example; if I have

class Person {
public string Name;
public string LastName;
}
class President : Person {
public string password;
}

main(){
President pr = new President() {Name="John"; LastName="Smith"; password="js123" };
Person p = (Person)pr;
SendToAirportSystemAcrossInternet(p);
}

虽然我们认为的 P 的是的,但它不是!它的的 president P 的距离就看,所以president的密码将在互联网上旅行!

While we think that p is a Person but it's not! it's the President and p is just a view from it, so the president's password will travel across the Internet!

有关如何修剪或切片对象到它的基地,创造一个真正的基础对象,你知道吗?

Any idea about how to prune or slice an object to it's base to creating a real base object?

在此先感谢!

推荐答案

这不是很明显你想要什么来实现的,但是当你有兴趣的对象的继承层次,你很可能要处理的情况下, 。对的System.Type 这里是您发布的第一种方法的一个工作版本,它可能给你如何从那里继续一个提示:

It's not quite obvious what you're trying to achieve, but as you're interested in your object's inheritance hierarchy you'll most likely want to deal with instances of System.Type. Here's a working version of the first method you posted which might give you a hint on how to proceed from there:

static void PrintObjectHierarchy(object o)
{
    Type t = o.GetType();
    while (t != null)
    {
        Console.WriteLine(t.FullName);
        t = t.BaseType;
    }
}

这篇关于你如何修剪对象在C#.NET其基本对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆