反射到Get`Parent`对象

本文关键字:Parent 对象 Get 反射 | 更新日期: 2023-09-27 18:27:44

我很确定这是不可能的,但我想我无论如何都会问。

假设我有:

public class A
{
    public B BInstance { get; set; }
}
public class B
{
    public Type GetParentType()
    {
        //...
    }
}

对于BGetParentType,有没有可能通过反射在运行时返回typeof(A)

我知道当我在A上初始化它时,我可以简单地将typeof(this)传递到B中,我只是很好奇。

反射到Get`Parent`对象

据我所知,答案是否定的,因为当你写时

var t = new B () ;

新的B实例没有关于将存储在哪里的信息,因此istance对存储在var中的事实没有认知,您的示例中不知道的那些实例被放在了a实例的属性中。

请不要真的这么做。。。

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Threading;
public class Program
{
    public static void Main()
    {
        var xx = B.GetParentType();
    }
}
public class A
{
    public B b { get; set; }
}
public class B
{
    public static List<Type> GetParentType()
    {
        var q = from t in Assembly.GetExecutingAssembly().GetTypes()
                where t.IsClass && t.GetProperties().Any(p => p.PropertyType == typeof(B))
                select t;
        return q.ToList();
    }
}

代码很乱,但它可以工作:

public class A { public B BInstance { get; set; } }
public class Z { public B BInstance { get; set; } }
public class C { public Z BInstance { get; set; } }
public class B
{
    public List<Type> GetParentTypes()
    {
        Type thisType = this.GetType();
        FieldInfo f = null;
        PropertyInfo p = null;
        Assembly assembly = Assembly.GetAssembly(thisType);
        List<Type> types = 
            assembly.DefinedTypes
            .Where(t => t.IsClass
                && t.GetMembers().Any(m =>
            {
                if ((f = m as FieldInfo) != null)
                    return f.FieldType == thisType;
                return (p = m as PropertyInfo) != null &&
                                 p.PropertyType == thisType;
            }))
            .Select(t => t.AsType())
            .ToList();
        return types;
    }
}
class Program
{
    static void Main(string[] args)
    {
        B instance = new B();
        List<Type> types = instance.GetParentTypes();
        foreach (var type in types)
        {
            Console.WriteLine(type.Name);
        }
    }
}

输出:

Z