c# - 当参数声明为基类型时,如何获取继承对象的属性?

标签 c# generics reflection

我有一个简单的程序,它使用反射打印出所提供类的属性和值。

class BaseClass
{
    public string A
    {
        get { return "BaseClass"; }
    }
}

class Child1 : BaseClass
{
    public string Child1Name {
        get { return "Child1"; }
    }
}

class Child2 : BaseClass
{
    public string Child2Name
    {
        get { return "Child2"; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var child1 = new Child1();
        var child2 = new Child2();
        SomeMethod(child1);
        SomeMethod(child2);

        Console.ReadKey();
    }

    static void SomeMethod(BaseClass baseClass)
    {
        PrintProperties(baseClass);
    }

    static void PrintProperties<T>(T entity)
    {
        var type = typeof(T);

        foreach (var targetPropInfo in type.GetProperties())
        {
            var value = type.GetProperty(targetPropInfo.Name).GetValue(entity);
            Console.WriteLine("{0}: {1}", targetPropInfo.Name, value);
        }
        Console.WriteLine("");
    }
}

问题是它只打印出 BaseClass 属性,因为我正在使用泛型并将 BaseClass 传递到 PrintProperties 方法中。

输出:

A: BaseClass

A: BaseClass

如何访问子类的属性?我想要这样的输出:

A: BaseClass
Child1Name: Child1

A: BaseClass
Child2Name: Child2

最佳答案

这里的问题是您在 PrintProperties 中使用了 typeof(T),但是您示例中的 T BaseClass 因为那是你从 SomeMethod 给它的参数类型。

在您的示例中,删除 SomeMethod,直接调用 PrintProperties 方法,它将起作用。

更简单的方法是使用 entity.GetType() 而不是 typeof(T)。这样,无论泛型类型是什么,您将始终获得对象的真实类型。

关于c# - 当参数声明为基类型时,如何获取继承对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29702972/

相关文章:

c# - 错误 : File Path is Too Long

c# - 如何向 Iron Python 添加模块?

java - 泛型:如何捕获通配符?

java - 方法与类型中的另一种方法具有相同的删除 - 第 2 部分

c# - 使用(FileStream)创建临时文件导致 "The process cannot access the file because it is being used"

c# - .NET 中类(对象)的大小

java - Autowiring 在 Spring 4 中不起作用

斯卡拉宏 : Add function to class

c# - 跨序列化对象反射以设置 PropertyChanged 事件

.net - 用于测试私有(private)方法的非代码生成的转发垫片