你如何修剪对象在C#.NET其基本对象?对象、基本、NET

2023-09-06 17:46:51 作者:剥开我的心脏看你的位置

考虑下面的方法:

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;
    }
}
 
精彩推荐
图片推荐